× back
Next Topic → ← Previous Topic

Exception handling

Now let's discuss exception handling ↓

Exception handling process

Syntax - Throw

  • The keyword throw is used to throw an exception.
  • Any expression can be used to represent the exception that has occured
                    
throw n;
throw (n);    
                    
                

Syntax - Try and Catch

                    
int main()
{
    try{
        ... 
    }
    catch(Exception1 obj)
    {
        ...
    }
    catch(Exception2 obj)
    {
        ...
    }
    return 0;
}
                    
                

Catch blocks

  • Catch handler must be preceded by a try block or any other catch handler.
  • Catch handlers are only executed when an exception has occured.
  • The catch blocks are tried in order they are written.

Let's understand with program

                   
#include <iostream>
using namespace std;

int main()
{
    int a, b, r;
    cout << "Enter the value of a : ";
    cin >> a;
    cout << "Enter the value of b : ";
    cin >> b;
    if (b != 0)
        r = a / b;
    else
    {
        cout << "Cannot divide by zero";
    }

    return 0;
}
                   
               

Output ↓

                
Enter the value of a : 12
Enter the value of b : 0
Cannot divide by zero
                
            

Now we will implement it using try and catch block

                   
#include <iostream>
using namespace std;

int main()
{
    int a, b;
    float r;
    cout << "Enter the value of a : ";
    cin >> a;
    try
    {
        cout << "Enter the value of b : ";
        cin >> b;
        if (b == 0)
            throw 0;
        r = a / b;
        cout << "The result if : " << r << endl;
    }
    catch (int)
    {
        cout << "cannot divide by zero" << endl;
    }
    return 0;
}
                   
                

Output ↓

                
Enter the value of a : 14
Enter the value of b : 0
cannot divide by zero
                
               
                
Enter the value of a : 15
Enter the value of b : 3
The result is : 5
                
               

Reference ↓