Concepts of throwing and catching exceptions - C++

Explain the concepts of throwing and catching exceptions.

- 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()
What are the advantages of “throw.....catch” in C++?
What are the advantages of “throw.....catch” in C++? - Code isolation: All code that is to be handled when an exception raises is placed....
What are friend classes? What are advantages of using friend classes?
What are friend classes? - The friend function is a ‘non member function’ of a class.....
What are zombie objects in C++?
What are zombie objects in C++? - An object creation of a class is failed before executing its constructor....
Post your comment