Exception Handling in C++ With Examples

In this article, we’ll take a look at performing Exception Handling in C++.

Exception Handling is an important topic, especially in the context of Object-Oriented Programming. C++ is similar to Java, with the fact that it can raise and catch Exceptions.

We denote a separate section of the code to handle exceptions, as they make things modular and easier for programmers. If any additional errors are detected, only the exception handling code must be modified.

We must enclose any code which throws an exception under a try block. So the three major parts of Exception Handling are:

  • The try block
  • Throwing an exception, using an optional object, along with the throw keyword.
  • A catch block, to handle the Exception. This block is usually immediately after the try block. The program will jump to this section immediately after a suitable exception is thrown.

The overall structure of the program will be:

Let’s investigate this in more detail, in the below sections.


Throwing an Exception in C++

In C++ terms, we call the raising of an exception as throwing an exception.

This is done using the throw keyword. This can take any object (or a primitive type) and pass it into the exception handling code.

The syntax for throwing an object is:

Now, the program is obviously not complete, since there is no catch block.

Let’s write that now!


Catching Exceptions

We mentioned that the program will jump from the try block to a suitable catch block, if available.

A catch block is of the following structure:

Whenever our function_call(x) makes x become negative, it will throw an exception, and a message will be printed.

Let’s look at the complete program now.

Since x was set to 0 initially, we will throw an exception, and print the modified value of x ( set to -10), showing that it has executed the catch block.

Also, notice that the line immediately below the function_call(x) statement never gets executed, since the program directly jumps to catch.

Output

Catch-All types of Exceptions

What if you want your code to handle all arbitrary kinds of exceptions? C++ introduces a feature which allows you to perform this, using a special matching object using ....

To catch all kinds of exceptions, we can write catch(...) to catch every object that we throw. This is called the Default Exception and is the fallback option, when we cannot match with any of the other exceptions.

To illustrate this, here is an example.

Output

As you can see, initially, when i = 0, it goes to the first catch block, since we return an integer.

But, after that, since we return the string “Default String”, it does not match with the first block, and it goes to the default block.

Unfortunately, C++ does not give us a way to pass the object in the default case, so we cannot get the “Default String” string. This shows that we must use this only for adding functionality to our code, to account for unknown errors.

Passing Pointers and References to Exceptions

This is also possible since we’re working with C++!

A general rule is to handle all the freeing related to the pointers in the exception handling code.

Let’s consider the below exception handler class MyException.

Instead of passing on the integer directly, we construct an exception class and pass a pointer to an object, which has the relevant error code and error message.

Here, you can see how powerful using an Exception Class handler for this is!

Not only can we add debug messages to it, in the constructor, but when we actually pass it around, we only move the pointer, which is 8 bytes only! This is something other languages like Java can’t do easily.

Output

Indeed, this is what we expect! Only for values of -1, -2, and -3, we’ve instructed the constructor to set error messages. For other values, it is simply a NULL string.


Additional Takeaways for Exception Handling in C++

  • When using try and catch blocks, there is NO implicit type conversion taking place. So a char is not converted to an int, when passed to exception handlers.
  • Always use a catch block if you use a try block. Otherwise, if you throw an exception, this will result in an abnormal termination of the program.
  • Modularize your code so that your core program logic is different from the Error handling logic. For Exceptions, try to use related Exception Handler classes and polymorphism to handle errors.
  • If you use raw pointers, always remember to free them in your catch blocks! If you find raw points too troublesome, use smart pointers instead!

I hope you found this article useful for learning more about Exception Handling in C++. If you have any doubts, or even found any mistakes, please do mention them in the comment section below!


References


By admin

Leave a Reply

%d bloggers like this: