C++ Exception Handling

A programmer can get many advantages while using the C++ programming language. It offers various features and functionalities to the programmers. C++ offers a very powerful feature named Exception Handling.

What is Exception Handling in C++?

Sometimes when you execute a program, you may face exceptions like run-time abnormal conditions. It arises due to some abnormal conditions such as dividing a number by zero. It arises while a program is running.

In C++, you can perform exception handling with the help of three keywords such as try, catch and throw.

  • try:- Mainly used to represent a block of code which might throw an exception.
  • catch:- block of code inside this keyword will get executed when an exception is thrown.
  • throw:- Mainly used to throw an exception.

Why to use C++ Exception Handling?

  • To handle errors, you can also use if-else statements in your program code. But it is bad practice to use if-else statements to handle errors. Because it will make your code less readable and maintainable. And also the conditions and the code to handle errors will get mixed up with the normal flow. That’s when, Exception handling becomes useful.
  • With the help of exception handling, you can specify the exception which a function throws using the throw keyword.
  • In C++, you can also create a hierarchy of exception objects, exceptions in namespaces or classes and categorize them according to types.

C++ Exceptions

In C++, while executing a program, different types of errors can occur like coding errors made by the programmer, wrong input errors and other errors.
Then it will give an error message. To put it short, it will throw you an exception.

try and catch C++

You have to use try and catch statements to perform exception handling in C++. The try block is used to represent a block of code which might throw an exception. And the catch block is used to handle that exception.

Syntax:-

If your try block raises more than one exception then you can use multiple catch statements to catch different types of exceptions.

try {
   // code
} catch( Exception_Name e1 ) {
   // catch block
} catch( Exception_Name e2 ) {
   // catch block
} 

Throwing Exceptions in C++

You can make use of throw statements to throw exceptions anywhere within the program code. Below is an example of throwing an example:-

int divide(int a, int b) {
   if( b == 0 ) {
      throw "You are dividing a number by 0!";
   }
   return (a/b);
}

The above will throw an exception when you are dividing a number by zero.

Catching Exceptions

The catch statement is useful to catch any exception. You can also specify what type of exception you want to catch.

try {
   // code
} catch( Exception1 e ) {
  // code to handle exception
}

The above will catch an exception named Exception1.

Example without try and catch statements

#include <iostream>
using namespace std;
int divide (int a, int b)
{
  return (a / b);
}

int main ()
{
  int x = 5;
  int y = 0;
  int z = 0;
  z = divide (x, y);
  cout << z << endl;
  return 0;
}

Output:-

Floating point exception

Writing the above program code with try and catch statements:-

#include <iostream>
using namespace std;
int divide (int a, int b)
{
  if(b==0){
  	throw "You are dividing a number by zero!";
  }
  return (a/b);
}

int main ()
{
  int x = 5;
  int y = 0;
  int z = 0;
  try{
  z = divide (x, y);
  cout << z << endl;
  }catch (const char* e){
  	cerr << e << endl;
  }

  return 0;
}

Output:-

You are dividing a number by zero!

Exception Handling in C++

1. In C++, you can make use of a special catch block named ‘catch all’ catch(…) which is used to catch all types of exceptions.

#include <iostream>
using namespace std;

int main()
{
    try {
    throw 5;
    }
    catch (char *exp) {
   	 cout << "Catch the Exception!" << exp;
    }
    catch (...) {
   	 cout << "Testing!\n";
    }
    return 0;
}

Output:-

Testing!

2. Primitive types cannot be implicitly converted. Below, ‘T’ is not implicitly converted to int.

#include <iostream>
using namespace std;

int main()
{
    try {
    throw 'T';
    }
    catch (int a) {
   	 cout << "Catch the expression!" << a;
    }
    catch (...) {
   	 cout << "Just Testing!\n";
    }
    return 0;
}

Output:-

Just Testing!

3. Suppose an exception is thrown and if it did not catch anywhere then the program will terminate abnormally.

#include <iostream>
using namespace std;

int main()
{
    try {
    throw 'T';
    }
    catch (int a) {
   	 cout << "Catch an exception!";
    }
    return 0;
}

Output:-

terminate called after throwing an instance of ‘char’
Aborted

You can write your own unexpected function to change the above abnormality.

  • In C++, the compiler does not check if the exception is caught or not. But in Java, this is possible.
  • The C++ programming language has a special exception class which is the base class for all standard exceptions.
  • You can also perform nested try/catch statements. You can also rethrow an exception using ‘throw;’.
    #include <iostream>
    using namespace std;
    
    int main()
    {
        try {
       	 try {
       		 throw 10;
       	 }
       	 catch (int x) {
       		 cout << "Testing1.... \n";
       		 throw;
       	 }
        }
        catch (int x) {
       	 cout << "Testing2.... ";
        }
        return 0;
    }
    

    Output:-

    Testing1….
    Testing2….
  • Whenever an exception is thrown, the objects created inside the try/block statements are destructed.
    #include <iostream>
    using namespace std;
    class Tech{
    public:
      Tech() { cout << "It is the constructor of Tech!" << endl; }
      ~Tech() { cout << "It is the destructor of Tech!" << endl; }
    };
     
    int main()
    {
      try {
        	Tech t1;
        	throw 5;
      }
      catch (int x) {
        	cout << "Catch an exception " << x << endl;
      }
    }
    

    Output:-

    It is the constructor of Tech!
    It is the destructor of Tech!
    Catch an exception 5

C++ Standard Exceptions

C++ also offers various standard exceptions which are defined in <exception>. You can use these in your program.
Below is the table of the standard exceptions:-

Serial No. Exception and Definition
1 std::exception

It is the parent class of all standard C++ exceptions. Also an exception.

2 std::bad_alloc

Used to throw exceptions by new.

3 std::bad_cast

Used to throw exceptions by dynamic_cast.

4 std::bad_exception

Used to handle unexpected exceptions.

5 std::bad_typeid

Used to throw exceptions by typeid.

6 std::logic_error

You can easily detect an exception just by reading the code.

7 std::domain_error

Used to throw an exception whenever a mathematically invalid domain is used.

8 std::invalid_argument

Exception is thrown due to invalid arguments.

9 std::length_error

Exception is thrown whenever a too big std::string is generated.

10 std::out_of_range

Exception is thrown by the ‘at’ method.

11 std::runtime_error

You cannot detect an exception by reading the code.

12 std::overflow_error

In the program code, if a mathematical overflow occurs then this exception is thrown.

13 std::range_error

Exception is thrown when you tend to store value out of the range.

14 std::underflow_error

In the program code, if a mathematical underflow occurs then this exception is thrown.

Defining New Exceptions in C++

In C++, you can also define your own exceptions. It can possible by inheriting and overriding exception class functionality.

#include <iostream>
#include <exception>
using namespace std;

struct JustException: public exception{
   const char * Tech() const throw () {
  	return "Testing C++ exception!";
   }
};
 
int main() {
   try {
  	throw JustException();
   } catch(JustException& e) {
  	std::cout << "Caught JustException!" << std::endl;
  	std::cout << e.Tech() << std::endl;
   } catch(std::exception& e) {
   }
}

Output:-

Caught JustException!
Testing C++ exception!

From above, Tech() is a public method that is provided by the exception class. And later, it is overridden by all the child exception classes.

Summary

In this tutorial, we discussed how you can perform exception handling in C++ in detail. We saw what exceptions are and how to handle them in C++. Then we discussed why to use exception handling. We talked over different aspects of exception handling in C++. We also discussed how you can define your own exception in C++.