C++ Exception Handling

This article explains exception handling in C++.

An “exception” refers to a problem that occurs during the execution of a program. Exception handling in C++ refers to the process where we deal with the error that has occurred.

All Exceptions in C++ are derived from the parent class, std::exception. Examples of exceptions in C++ include “Division by Zero” (where a division by zero was attempted) and out of range (where you attempt to access an element from an array index that doesn’t exist).

Normally when an error occurs, the entire program shuts down because it doesn’t know how to handle it. Exception handling (if implemented correctly) gives us the ability to keep the program running even if an error occurs.


Exception Handling Syntax

In order to deal or “handle” exceptions in C++ you need to make use of the try and catch keywords.

try {
   // code
 that might throw an exception
} catch( ExceptionName e1 ) {
   // code that deals with the exception
} catch( ExceptionName e2 ) {
   // code that deals with the exception
.
.
.
}

The code in the try block is that code where you might expect the exception to be thrown. Or perhaps you’ve even placed a throw statement their yourself (more on this later).

The code in the catch block is the code that runs if an exception is detected. What you place in this will depend on the complexity of the program and the type of error, but a simple prompt will suffice for most cases.


Throwing Exceptions

Whether it’s just for testing or real-life scenarios, you’ll often find the need to be throwing exceptions as well. This is possible with the help of the throw keyword.

The throw keyword can be used in variety of different ways. You can choose to either just use the throw keyword or throw a specific exception. We’ll be demonstrating the use of this keyword with the below examples.

#include <iostream>
using namespace std;

int main () {
  try
  {
    throw runtime_error("Zero Division Error");
  }
  catch (exception& e)
  {
    cout << e.what() << endl;
  }
  return 0;
}
Zero Division Error

A list of common exceptions that occur in C++: (You can remove the std:: if you’ve used the using namespace std command)

  • std::bad_cast
  • std::logic_error
  • std::invalid_argument
  • std::out_of_range
  • std::range_error
  • std::runtime_error
  • std::overflow_error

Exception Handling Examples

Example 1:

The catch keyword can take a variety of different forms. In the previous example we used it to take as parameter the exception that occurred. In this example we demonstrate a catch statement which activates when any type of exception is thrown.

#include <iostream>
using namespace std;

int main () {

  try
  {
    throw runtime_error("");
  }
  catch (...)
  {
    cout << "Error Detected!";
  }
  return 0;
}
Error Detected!

Example 2:

In the first example the catch statement took the exception that occurred as a parameter. We can also pass other things like integers, characters, or strings. Basically the below catch statement is setup to receive any exceptions with integers (A throw statements that “throws” integers).

If you try to throw anything but an integer in the below example, the program will terminate right at the throw statement. You’ll need to have other catch statements set up in order to avoid this (we’ll cover this in the next section).

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

int main () {
  int x = 5;

  try
  {
    throw x;
  }
  catch (int x)
  {
    cout << "Error Detected!" << endl;
    cout << "Value of X: " << x << endl;

  }
  return 0;
}
Error Detected!
Value of X: 5

Example 3

In the following example we’ll demonstrate the use of multiple catch statements. The reason for this being that often the standard “...” catch exception is not specific enough. And neither can you have just one specific catch statement (else the problem mentioned above will occur).

The benefit of the below code is that it doesn’t have the same weakness as the previous example (example 2). In example two, if anything but an integer variable was thrown, the program would terminate because there was no catch statement to receive it.

This example shows that even if an integer variable is not thrown, the last catch statement will “catch” and handle it properly. In the event an integer variable is thrown, the program flow will reach the 1st catch statement first, and will never go to the second.

#include <iostream>
using namespace std;

int main () {
  string x = "Hello";

  try {
    throw x;
  }
  catch (int x) {
    cout << "Error Detected!" << endl;
    cout << "Value of X: " << x << endl;
  }
  catch (...) {
      cout << "Default Exception";
  }
  return 0;
}
Default Exception

As a disclaimer, alot of the examples here were for explanatory purposes. Exception handling isn’t really used in simple (small) programs so it’s bit difficult to come up with a real life example. Learn the concepts explained above and implement them when the time comes.


This marks the end of the C++ Exception Handling tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the article content can be asked in the comments section below.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments