Exception Handling

Exception handling :

Exception are the errors occurring at time of program execution or run-time like divide by zero error.
Exception handling is done to transfer the control of programs in case exceptions occur.
C++ exception handling is built upon three keywords: try, catch, and throw.
Syntax : 

  • Program statements that may throw or raise an exception are contained in a try block.
  • Functions called from within a try block may also throw an exception.
  • Exceptions thrown by try block are caught by a catch statement, which immediately follows the try statement in which the exception was thrown.
  • There can be more than one catch statement associated with a try block.
  • When an exception is thrown, it is caught by its corresponding catch statement, which processes the exception if the data type specified by a catch matches that of the exception, then that catch statement is executed.

throw :

throw raises the exception specified by exception.

Syntax :
throw exception;
  • If this exception is to be caught, then throw must be executed either from within a try block itself, or from any function called from within the try block.
  • Throwing an unhanded exception causes the standard library function terminate() to be invoked. By default, terminate() calls abort() to stop your program, but you can specify your own termination handler.
  • However, if an error cannot be fixed, then, a catch block will terminate the program with a call to exit() or abort() .

  • Most of the times Exception are thrown and caught using objects rather primitive data types because classes better help to describe the errors that occur.


  • If Exception class has a derived class and you want to catch exceptions of both a base class type and a derived class type, put the derived class first in the catch sequence. If you don’t do this, the base class catch will also catch all derived classes.



  • To catch all exceptions of any type use following catch :

catch(…) {
…Common Actions for all exceptions

  • It provides a final or default catch statement for a try block when none of the specified type of exception occurs.


  • Type of exceptions that a function can throw outside of itself can be restricted.

Syntax :
return_type func(arg_list) throw(type_list)


  • Attempting to throw an exception that is not supported by a function will cause the standard library function unexpected() to be called. By default, this causes abort() to be called, which causes abnormal program termination.
Posted in: C++

Leave a Reply

Your email address will not be published. Required fields are marked *