C++ Exceptional Handling

Exceptional Handling

An exception is a problem that arises during the runtime of a program. C++ exception handling is a response to an exceptional circumstance that arises while a program is running. We implement exception handling so the control flow of the program can be maintained even after runtime errors.

Exception handling in C++ grants us a way of handling unexpected situations like runtime errors, such as an attempt to divide by zero. So whenever an unforeseen situation happens, an exception will be thrown and the control flow of the program is transferred to special functions known as handlers. The handler will take control of the program.

To catch the exceptions, code under exception inspection has to be placed in the program. The block of code is located within the try-catch block.

Exceptions give a way to transfer control flow from one to another part of the program. C++ exception handling is based upon three keywords: try, catch, and throw.

  • throw − Represents a block of code that throws an exception when an abnormal error shows up.
  • catch − Represents a block of code that catches the exception with an exception handler. The catch keyword shows the catching of an exception.
  • try − A try block recognizes a block of code for which particular exceptions will be activated.

Why Exception Handling? 
Following are the main advantages of exception handling over traditional error handling.

1) Separation of Error Handling code from Normal Code: The program becomes more readable and easier to understand and maintain.

2) Functions/Methods can handle any exceptions they choose: Functions can control the exceptions they choose. Even if a function throws multiple exceptions, it will only handle some. The caller will have to handle the uncaught exceptions.

Throwing Exceptions

Exceptions can be thrown from any place within a block of code using the throw statement. The operand of the throw set of statements concludes the type for the exception and the type of the result of the expression determines the type of exception thrown.

Below is an example of throwing an exception when dividing a number by zero condition occurs −

double division(int a, int b) 
{
   if( b == 0 ) 
   {
      throw "Division by zero exception";
   }
   return (a/b);
}

Try/Catch block

A try/catch block is set around the code that might create an exception. Code within the try/catch block is referred to as a protected code.
Syntax:

try 
{
   // protected code
} 
catch( ExceptionName e1 ) 
{
   // catch block
} 
catch( ExceptionName e2 ) 
{
   // catch block
} 
catch( ExceptionName eN ) 
{
   // catch block
}

Catching Exceptions

The catch segment following the try block catches any exception. You can define what type of exception you want to catch and this is defined by the exception declaration that appears in parentheses following the keyword catch.

try 
{
   // protected code
} 
catch( Exception_Name e ) 
{
  // body of code to handle Exception_Name exception
}

The following is an example, which throws a division by zero exception and we catch it in catch block.

#include <iostream>
using namespace std;

double division(int x, int y) {
   if( y == 0 ) {
      throw "Division by zero error";
   }
   return (x/y);
}

int main () {
   int a = 50;
   int b = 0;
   double c = 0;
 
   try {
      c = division(a, b);
      cout << c << endl;
   } catch (const char* msg) {
     cerr << msg << endl;
   }

   return 0;
}

C++ Standard Exceptions

C++ gives a list of standard exceptions specified in <exception> which can be used in the programs. They are arranged in a parent-child class hierarchy shown below −

Sr.NoException & Description
1std::exception An exception and parent class of all the standard C++ language exceptions.
2std::bad_alloc Can be thrown by new.
3std::bad_cast This can be thrown by dynamic_cast.
4std::bad_exception Useful to handle unexpected exceptions in a code.
5std::bad_typeid This can be thrown by typeid.
6std::logic_error An exception that can be detected by reading the program.
7std::domain_error This exception is thrown when a mathematically invalid domain is used.
8std::invalid_argument This is thrown due to invalid arguments.
9std::length_error This is thrown when a too big std::string is created.
10std::out_of_range This can be thrown by the ‘at’ method.
11std::runtime_error An exception that cannot be detected by reading the code.
12std::overflow_error This is thrown if a mathematical overflow occurs.
13std::range_error Occurs when out of range value is tried to store.
14std::underflow_error This is thrown if a mathematical underflow occurs.

Stack Unwinding in C++

Stack Unwinding is a process of removing function entries from the function call stack at run time. Stack Unwinding is usually associated with Exception Handling that is Stack elements can be removed with the help of exceptions. In C++ Language, when an exception happens, the function call stack is linearly searched for the exception handler, the entries before the function with exception handler are eliminated from the function call stack and return to the main invoker function.

When we call a function, it holds the address into the call stack, and after returning back from the function, pops out the address to begin the work where it was left of.

void func( int x )
{
    char* pleak = new char[1024]; // might be lost => memory leak
    std::string s( "hello world" ); // will be properly destructed

    if ( x ) throw std::runtime_error( "boom" );

    delete [] pleak; // will only get here if x == 0. if x!=0, throw exception
}

int main()
{
    try
    {
        func( 10 );
    }
    catch ( const std::exception& e )
    {
        return 1;
    }

    return 0;
}

When an exception is thrown and control flow passes from a try block to a handler, the C++ run time calls the destructors for all the automatic objects constructed since the start of the try block. This method is called stack unwinding. The automatic objects are destroyed in reverse order of their construction.

We will be happy to hear your thoughts

Leave a reply

Edusera
Logo
Open chat
1
Scan the code
Hello!👋
Can we help you?