티스토리 뷰


Exception handling in C++ 


Exception handling is the method you use to make the program work normally under abnormal circumstances(with different errors) but Try, Throw and Catch can't replace every error handling circumstance because it could cause poor performance. It is good to use for the situation which happened difficult to predict the result. But, Try, Throw and Catch strictly handle type conversion. 






Example


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <string>
 
using namespace std;
int main()
{
    int a, b;
    cout << "Input two numbers: ";
    cin >> a >> b;
 
    try // Code which could cause exception
    {
        if (b < 1 || a < 1)
        {
            throw string("Error occured"); //throw - throw an exception 
        }
        cout << a << "  can not be devided by " << b << " , " << a / b << endl;
    }
    catch (string errMessage) //catch - catches an exception with an exception handler
    {
        cout << errMessage << endl;
    }
    
    return 0;
}
cs




Result