Posted January 25, 2011 by Spyros in C/C++ Programming

Exception Handling in C++ ( Use Try, Catch)


Handling exceptions in C++ is a quite easy, but pretty imporant procedure. You go even go about creating your own class that would handle exceptions locally. The idea is that you define your set of functions that checks for certain conditions and throw exceptions if they are not met. Basic exception handling usage involves using the try and catch commands. Inside the try block, you insert the code that you want to check for exceptions, while inside catch is the actual exception handling procedure. This is an example, handling a division by zero exception :

#include <iostream>
using namespace std;

#define DivisionByZero 1

int main()
    int x = 5;
    int y = 0;
        if (y == 0)
            throw DivisionByZero;
        int z = x/y;
    catch (int exception_number)
        if (exception_number == DivisionByZero)
            cout << "Division By Zero is not allowed !" <<  endl;
    return 0;

We define a constant of DivisionByZero to be equal to 1. Then, inside the try block, we check whether y is 0 or not. If so, we throw a DivisionByZero exception, that has 1 as its exception_number. Then, the catch block catches the exception and executes our code, which in turn prints out a string, informing us about the problem.