I have forgotten
my Password

Or login with:

  • Facebookhttp://facebook.com/
  • Googlehttps://www.google.com/accounts/o8/id
  • Yahoohttps://me.yahoo.com

Valid RSS




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.

Exception Description
bad_alloc thrown by new on allocation failure
bad_cast thrown by dynamic_cast when fails with a referenced type
bad_exception thrown when an exception type doesn't match any catch
bad_typeid thrown by typeid
ios_base::failure thrown by functions in the iostream library

Example - nested try-catch
This simple program illustrates 2 nested try-catch.
#include <iostream>
#include <conio.h>
using namespace std;
int main()
         throw 5;
      catch(int e)
	 throw 10;
   catch(int e)
      cout <<"Exception "<<e<<"."<<endl;
  return 0;

Exception 10.