Summary: In this tutorial, we will learn what an exception is, how many types it has, and how we can handle them in C++.

What is an Exception in C++?

An exception is any unwanted situation that occurs during the runtime of the program.

It is an error that is not detected during compile time but comes into effect during the execution of the program.

Some common exceptions that often occurs in C++ are:

  • IndexOutOfBoundsException: It occurs when the program tries to access the index of an object that is out of its range.
  • IOException: This exception occurs in multiple cases. One such situation is when the user enters the wrong type of input during runtime e.g. a string instead of an integer.

How to Handle Exceptions in C++?

Although exceptions occur during runtime, we can still speculate and handle them using the try and catch block in C++.

try and catch Block

In the try block, we write the set of codes that could potentially throw the exception, and in the catch block, we catch those exceptions.

try{
    //code prone to errors 
} 
catch(Exception &e){
   //do something 
}

The code inside the catch block is executed only if the exception type specified in its argument has occurred in the try block.

For example, the following snippet can only catch IOException, if it occurs in the try block:

try{
    //code prone to errors 
} 
catch(IOException &e){
   //do something 
}

To catch multiple exceptions, we can write multiple catch blocks such as the following:

try{
    //code prone to errors 
} 
catch(IOException &e){
   //do something 
}
catch(IndexOutOfBoundsException &e){
   //do something 
}

We can also catch all types of exceptions in the same catch block using ellipsis as an argument (i.e. …):

try{
    //code prone to errors 
} 
catch(...){
   //do something 
}

It’s a good practice to use ellipsis catch block with other catch blocks catching specific exceptions.

Note: If you are writing an ellipsis catch block with other catch blocks, it is recommended to write it to the last. Because the exception is caught in order. If we write the ellipsis block first it will catch all kinds of exceptions and make the latter block redundant.

throw Keyword

The throw keyword is used to explicitly throw an exception from a try block.

try{
    //code 
    throw Exception();
} 
catch(Exception &ex){
   //do something 
}

C++ Example using try, catch & throw

#include <iostream>
using namespace std;
 
double divide(double num, double den){
    //throwing an string as exception
    if(num <= 0 || den <= 0)
        throw string{"Negatives and Zero are not allowed"};
        
    return num/den;
}
 
int main()
{
    int a=4, b=-1, quotient;
    
    try{
        quotient = divide(a, b);
        cout << a << "/" << b << "= " << quotient;
    } catch(string &s){
        cout << s << endl;
    } 
}

Output:

Exception handling in C++

In C++ when we divide an integer by 0, it returns inf. We don’t want this to happen, instead we want the program to throw an exception.

Therefore, to accomplish this we increase a string type exception using the throw keyword in particular.

Since the divide method is called from inside the try block, the exception thrown by it is caught by the corresponding catch block.

User-Defined Exception

Exceptions are nothing but predefined classes in C++ libraries.

For example, IOException: This is a class and whenever an IO error occurs during runtime, the interpreter throws an instance of it, which we need to catch.

Similarly, we can define our own classes and treat them as exceptions (like in the previous example we have treated string as exception).

Hence, to create a user-defined exception create a class with the name of the exception:

class DivideByZeroException {};

C++ Example Using User-Defined Exception

#include <iostream>
using namespace std;
 
class DivideByZeroException {
};
 
class NegativeValueExeption {
};
 
double divide(double num, double den){
    if(den == 0)
        throw DivideByZeroException();
    if(num < 0 || den < 0)
        throw NegativeValueExeption();
    return num/den;
}
 
int main()
{
    try{
        int quo = divide(4, 0);
        cout << "Quotient is: \n" << quo;
    } catch (DivideByZeroException &ex){
        cout<< "Cannot divide by zero \n";
    } catch(NegativeValueExeption &ex){
        cout << "Negative numbers not allowed \n";
    }
}

Output:

Try catch throw

In this example, we have created two empty classes with corresponding error names, so that we can throw their objects when required.

Once the object thrown from the try block is caught by any catch block, we display the appropriate message.

In this tutorial, we learned how to handle exceptions in C++ by try and catch block, and create our own exception and raise them using the throw keyword in C++.

Leave a Reply