Logo F2FInterview

C++ Interview Questions

Q   |   QA

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().

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: