You're viewing an older version of this page (#4225). View the current version.

View versions (1)

Definition

Exceptions occur because of problems arising at runtime (memory overflow, data outside the prescribed limits) and provide a way to react to exceptional circumstances.

Try, Catch, Throw

try {
   // code that could throw an exception
}
[ catch (exception-declaration) {
   // code that executes when exception-declaration is thrown
   // in the try block
}
[catch (exception-declaration) {
   // code that handles another exception type
} ] . . . ]
// The following syntax shows a throw expression:
throw [expression]

The try, throw, and catch statements implement exception handling.

The code after the try clause is the guarded section of code. The throw expression raises an exception. The code block after the catch clause is the exception handler, and handles the exception thrown by the throw expression. The exception-declaration statement indicates the type of exception the clause handles. The type can be any valid data type, including a C++ class.

The operand of throw is syntactically similar to the operand of a return statement.

Standard Exceptions

The C++ Standard library provides a base class named exception specifically designed to declare objects to be thrown as exceptions, which is defined in the <exception> header file under the namespace std.

ExceptionDescription
bad_allocthrown by new on allocation failure
bad_castthrown by dynamic_cast when fails with a referenced type
bad_exceptionthrown when an exception type doesn't match any catch
bad_typeidthrown by typeid
ios_base::failurethrown by functions in the iostream library

References

Example 1
Problem

This simple program illustrates 2 nested try-catch.

Workings
#include <iostream>
#include <conio.h>

using namespace std;

int main()
{
  try
   {
      try
      {
         throw 5;
      }
      catch(int e)
      {
	 throw 10;
      }
   }
   catch(int e)
   {
      cout <<"Exception "<<e<<"."<<endl;
   }

  _getch();
  return 0;
}
Solution

Output:

Exception 10.