Exception Handling in C++

  During your interaction with C++, you might have come across certain errors which pop up out of nowhere in the middle of execution of a program. A strange situation which you hadn’t imagined earlier – which may be a case of division by zero, or an overflow, or a failed memory allocation or any other similar undesirable event, appears unexpectedly and then your program terminates πŸ™ . This, as you might already know, is called an EXCEPTION. This article is focussed at Exception Handling in C++.

Exception Handling in C++

An Exception is a problem that arises during the execution of a program. It happens under circumstances which are usually unexpected in the normal course of the program, hence the name ‘exception’.



Since an exception leads to undefined behaviour and often causes the program to terminate, it is crucial for you as a programmer to handle exceptions appropriately.

Exception Handling in C++

In C++, the whole task of Exception Handling is performed using three keywords : try, catch and throw. Of these keywords, try and catch are used alongwith a block of statements, which are known as the try block and the catch block, respectively. The throw keyword is used to throw exceptions manually i.e. we test for a certain condition and if that condition occurs, we throw an exception.

The try block

As mentioned above, the try keyword is used with a block of statements, which is known as the try block.

A try block is always followed by one or more catch blocks.

A try block contains the statements in which an exception may occur.

  • In case an exception occurs inside the try block, the control shifts to the catch block where the appropriate task is performed.
  • If no exception occurs, the subsequent catch block(s) is/are skipped, and the program continues it normal operation.

A try block has the following syntax:

try
{
    // statement(s) to be monitored for exceptions
}

For example, a typical try block looks like this:


try
{
    a = b/c;    // This statement will generate an exception
                // if the value of c at runtime is 0
}

The catch block

Β A try block is always followed by one or more catch blocks. If the programmer is sure that a try block may throw only one type of exception, then only one catch block is used. In case the occurrence of more than one exception is possible, multiple catch blocks are used. Each catch block handles a specific type of exception.

For example, one catch block may handle ‘division by zero’ type of exception, while another block may handle ‘out of bounds’ exceptions.

The syntax of a catch block is:


catch (ExceptionName variablename)
{
    // statements to be executed if this type
    // of exception is caught
}

For example, a typical catch block looks like:


catch (std::out_of_range s1)
{
    std::cout<<"The exception has been caught \n";
    std::cout<<" Press Y to continue exceution or any other key to exit the program";
    if (((ch = getchar()) == 'Y') || ((ch = getchar()) == 'y'))
       break;
    else
       exit(0);
}

If you want to create a generic catch block i.e. a catch block that is capable of handling all types of exceptions, you MUST put an ellipsis i.e. in the parantheses next to the catch keyword.


catch (...)
{
    // statements
}

The throw statement

The throw statement is used to throw exceptions manually i.e. by explicitly specifying the name of the exception to be thrown and caught. As you know, an exception thrown by a throw statement is caught by a catch block.

The syntax of the throw keyword is:


throw <exception-name>;

For example,


double arrchk(int r, int n)
{
   if( r > n )
   {
      throw range_error;
   }
   return (a/b);
}

A sample program

A sample program that catches and throws an exception using a try block and a catch block


#include <iostream>

using namespace std;

double divide (int x, int y)
{
    if (y == 0)
        throw "Cannot divide a number by zero";
    return x/y;
}

int main ()
{
    int x, y, z;

    cout << " Enter two numbers : ";
    cin >> x >> y;

    try
    {    
        z = divide (x, y);
        cout << x << "/" << y << " = " << z;
    }
    catch (const char *msg)
    {
        cerr << msg << endl;
    }
    getchar ();
    return 0;
}

The above program will throw an exception if the user enters 0 as the value of y, otherwise it will display the value of x/y. Here, the exception to be thrown is of the type const char *, therefore the catch() contains const char *msg in order to catch it.

The following message would be displayed by the above program in case the exception occurs:


Cannot divide a number by zero

If the exception was of the type range_error or overflow_error or any other type, the catch() would contain a declaration of that particular type.



How to Define your own exception type

You can define your own exceptions. To do this, you need to inherit and override the functionality of the exception class.


#include <iostream>
#include <exception>

using namespace std;

class MyEx : public exception
{
public:
    const char * what () const throw ()
    {
        return "Hahaha.. Finally Found the Exception";
    }
};

int main ()
{
    try
    {
        throw MyEx ();
    }
    catch (MyEx& me)
    {
        cout << "Are you looking for me? "<<endl;
        cout << me.what () << endl;
    }
}

As you can see in the above program, the class MyEx inherits the class exception. It also overrides the what () of the class exception. what () is a public function and it has to be overridden in order to show the cause of the exception defined by us i.e. MyEx. What happens inside the main () is quite clear. The try block throws an exception of the type MyEx which is caught by the subsequent catch block. The catch block tells the user that the exception has been caught and then displays the cause of the exception. You may also include other catch block(s) for catching other exception(s).

The above program has the following output:


Are you looking for me?
Hahaha.. Finally Found the Exception



Summary

Exception Handling in C++ is a vast topic in itself. This article was intended to give you a basic idea how exception handling in c++ works. We hope it helps you understand the mechanism of exception handling. In other languages like Java, the process of throwing and catching exceptions is similar. You must always provide a suitable exception handling mechanism in your programs. You certainly don’t want the users of your program(s) to be overwhelmed by the exceptions in them. Wherever you suspect the possibility of an exception, don’t wait. Just try () and catch (). πŸ˜€

(Visited 813 times, 1 visits today)

4 comments

  • Unhandled Exception

    Nice article. Before reading this article, I thought exceptions were a problem of Java only. I’ve seen several java based apps and games crash with an error like “java.blah.blah” type exceptions. Now, I know about exceptions in C++ and how to prevent them. Thanks!

  • Another great article from you. Dude, I want to set up a website of my own for hosting my articles and projects, like you have done. Would you guide me?

  • Exception Handling is something that every programmer should know. God knows when an unexpected exception sneaks in and ruins user experience. I like this article for it elaborates the basics of exception handling perfectly.

Leave a Reply

Your email address will not be published. Required fields are marked *