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