C에서는 보통 예외처리라 하면 조건문? 아니면 assert? 정도 일듯한데,
객체지향의 C++은 try~catch 구문이 있다.
아래 코드는 chatgpt가 생성해준 코드인데, 심플해서 이해하기 좀 쉽네.
#include<iostream>
#include<stdexcept>
using namespace std;
double divide(int numerator, int denominator)
{
if(denominator == 0)
{
throw invalid_argument("Division by zero is not allowed");
}
return static_cast<double>(numerator / denominator);
}
int main()
{
try{
int numerator, denominator;
// Get input from the user
cout << "Enter numerator: ";
cin >> numerator;
cout << "Enter denominator: ";
cin >> denominator;
double ret = divide(numerator, denominator);
cout << "result: " << ret << endl;
} catch(const exception& e){
cerr << "Exception caught: " << e.what() << endl;
}
return 0;
}
'C++' 카테고리의 다른 글
c++에서 vector에 접근하는 4가지 방법 (0) | 2024.01.21 |
---|---|
inline function defined in source file? or header file? (0) | 2024.01.20 |
while(cin >> x) (0) | 2024.01.20 |
switch-case (0) | 2022.06.11 |
down up casting (0) | 2022.06.08 |