try {
// 예외가 발생할 가능성이 있는 코드
} catch (예외 타입 변수) {
// 예외 처리 코드
}
#include <iostream>
using namespace std;
int divide(int a, int b) {
if (b == 0) {
throw "Division by zero error!"; // 예외 발생
}
return a / b;
}
int main() {
try {
cout << divide(10, 0) << endl;
} catch (const char* msg) {
cerr << "Caught exception: " << msg << endl;
}
return 0;
}
출력 예)
Caught exception: Division by zero error!
try {
throw 42;
} catch (int e) {
cout << "Caught an integer: " << e << endl;
} catch (double e) {
cout << "Caught a double: " << e << endl;
} catch (const char* e) {
cout << "Caught a string: " << e << endl;
}
try {
throw 3.14;
} catch (...) {
cout << "Caught an unknown exception" << endl;
}
#include <iostream>
#include <stdexcept>
using namespace std;
class MyException : public exception {
public:
const char* what() const noexcept override {
return "Custom exception occurred!";
}
};
int main() {
try {
throw MyException();
} catch (const MyException& e) {
cout << e.what() << endl;
}
return 0;
}
출력 예)
Custom exception occurred!
int x = 10; // 정수 리터럴
char ch = 'A'; // 문자 리터럴
double pi = 3.14; // 실수 리터럴
const int MAX_USERS = 100;
MAX_USERS = 200; // 오류! 상수는 변경 불가능
constexpr int square(int x) { return x * x; }
constexpr int result = square(5); // 컴파일 타임에서 계산됨
- const는 런타임에도 값을 결정할 수 있다
- constexpr은 반드시 컴파일 타임에 계산 가능해야 한다
#define PI 3.141592
std::cout << PI; // 3.141592
int a = 10, b = 20;
const int* p1 = &a; // p1이 가리키는 값을 변경할 수 없음
int* const p2 = &a; // p2가 다른 주소를 가리킬 수 없음
const int* const p3 = &a; // p3는 값도 변경 불가능, 주소도 변경 불가능
void printValue(const int x) {
// x = 100; // 오류 발생! x는 변경 불가
std::cout << x << std::endl;
}
class MyClass {
public:
void showValue() const { // 이 함수는 멤버 변수를 변경할 수 없음
std::cout << "This is a constant function" << std::endl;
}
};
#include <iostream>
#include "myheader.h" // 사용자 정의 헤더 포함
#ifdef DEBUG
std::cout << "디버그 모드 활성화";
#endif
namespace First {
int value = 10;
}
namespace Second {
int value = 20;
}
std::cout << First::value; // 10
std::cout << Second::value; // 20
using namespace std;
std::cout << "Hello, World!";