Logo F2FInterview

C++ Interview Questions

Q   |   QA

Exception handling in C++ is implemented by using the try{} and catch(){} statements.

When a try block throws an exception, the program leaves the try block and enters the catch statement of the catch block.

If they type of the object thrown matches the arg type in the catch block, catch block is executed for handling the code.

If they are not caught, abort() function is executed by default.

When no exception is deteted or thrown then the control goes to the statement below the catch block.

C++ provides a mechanism to handle exceptions which occurs at runtime. C++ uses the keywords – throw, catch and try to handle exception mechanism. An entity called an exception class need to be created.

The application should have a separate section called catch block. The code in which an exception is predicted is authored in the try block.

The following code illustrates to handle the exception.

#include <iostream>
class Excep {
public:
      const char* error;
      Excep(const char* arg) : error(arg) { }
};

class Test {
   public:
        int i;
    // A function try block with a member initializer
      Test() try : i(0) {
             throw Excep("Exception thrown in A()");
       }
       catch (Excep& e) {
             cout << e.error << endl;
       }
};

// A function try block
void f() try {
      throw E("Exception thrown in f()");
}
catch (Excep& e) {
     cout << e.error << endl;
}
void g() {
     throw Excep("Exception thrown in g()");
}

int main() {
   f();
    // A try block
    try {
       g();
    }
     catch (Excep& e) {
          cout << e.error << endl;
     }
      try {
           Test x;
      }
      catch(...) { }
}

The following is the output of the above example:
Exception thrown in f()
Exception thrown in g()
Exception thrown in A().

terminate() is a library function which by default aborts the program

It is called whenever the exception handling mechanism cannot find a handler for a thrown exception.

unexpected() is called when a function with an exception specification throws an exception of a type that is not listed in the exception specification for the function
A function declaration without a specification like throw(char*) may throw any type of exception, and one with throw() is not allowed to throw exceptions at all.

By default unexpected() calls terminate().

Exceptions: Exceptions are certain disastrous error conditions that occur during the execution of a program. They could be errors that cause the programs to fail or certain conditions that lead to errors. If these run time errors are not handled by the program, OS handles them and program terminates abruptly, which is not good. So C++ provides Exception Handling mechanism. 

Exceptions are of two types:

Synchronous Exceptions: Errors that occur due to incorrect input data or incorrect handling of array indices (“out of range index”), memory overflow are known as Synchronous Exceptions

Asynchronous Exceptions: The errors that are caused by events that are beyond control of the program are Asynchronous Exceptions. E.g. Keyboard interrupts

C++ exception handling mechanism takes care of only Synchronous Exceptions.

The benefits of Exception Handling are:

  1. Program is not terminated abruptly
  2. User will understand what errors are occurring in the program.

The three keywords for Exception Handling are:
Try, Catch and Throw.

The program tries to do something. If it encounters some problem, it throws an exception to another program block which catches the exception.

Consider following program code:

void main()
{
     int no1, no2;
     try
     {
         cout << “Enter two nos:”;
         cin >> no1 >> no2;
         if (no2 == 0)
             throw “Divide by zero”;
         else
             throw no1/no2;
     }
     catch (char *s)
     {
         cout << s;
     }
     catch (int ans)
     {
         cout << ans;
     }
}

We know that divide by zero is an exception. If user enters second no as zero, the program throws an exception, which is caught and an error message is printed.

Please note that catch is not a function; it is a program block.

Rethrowing an expression from within an exception handler can be done by calling throw, by itself, with no exception. This causes current exception to be passed on to an outer try/catch sequence. An exception can only be rethrown from within a catch block. When an exception is rethrown, it is propagated outward to the next catch block.

Consider following code:

#include <iostream>
using namespace std;
void MyHandler()
{
        try
        {
                 throw “hello”;
        }
        catch (const char*)
        {
               cout <<”Caught exception inside MyHandler\n”;
               throw; //rethrow char* out of function
        }
}
int main()
{
            cout<< “Main start”;
            try
            {
                   MyHandler();
            }
            catch(const char*)
            {
                  cout <<”Caught exception inside Main\n”;
            }
                  cout << “Main end”;
            return 0;
}

O/p:
Main start
Caught exception inside MyHandler
Caught exception inside Main
Main end
Thus, exception rethrown by the catch block inside MyHandler() is caught inside main();

In order to link this F2FInterview's page as Reference on your website or Blog, click on below text area and pres (CTRL-C) to copy the code in clipboard or right click then copy the following lines after that paste into your website or Blog.

Get Reference Link To This Page: (copy below code by (CTRL-C) and paste into your website or Blog)
HTML Rendering of above code: