C++ Exceptions

C++ Exceptions


C++ Exceptions
How to Deal with Exceptional States?
  • Ignore them:
  • Wrong thing to do for all but demo programs.
  • Abort processing – detect but don’t try to recover:
  • appropriate for programs with safety issues or critical missions.
  • Have functions return error codes:
  • Program is constantly spending CPU cycles looking for rare events.
  • Easy to miss a check.
  • Use C++ Exceptions
Exceptions use three keywords:
throw, try, and catch
  1. throw a:
    constructs an exception object, a, and takes it out of an enclosing context defined by a try block
  2. try {…}:
    defines, for thrown exceptions, an enclosing context with specified catch handlers
  3. catch(A a) {…}:
    exception handler catch(A a) responds to an exception object of type “A”
If no exception is thrown, the code in the try block is executed, the catch clause is skipped, and computation resumes after the catch clause.
For Example-The Syntax is as follows:
 
try 
  {
  // some code that may throw an exception
  }
  Catch(exception &e) 
  {
    // some processing to attempt to recover from error
    // based on information carried by the exception 
  }
If an exception is thrown somewhere in the try block, the remaining code in the try block is skipped,  and a matching catch clause is entered, if found.  Computation resumes after the last statement in matching catch clause.  Matching is based on the type of the exception.
Chained Handlers
Exception handlers are often chained at the end of a try block,
 For Example-The Syntax of Chained Handlers is as follows:
try {
  // some code that may throw an exception
  }
  Catch(T1 t1) {
    // processing for type T1 
  }
  Catch(T2 t2) {
  // processing for type T2
  }
Matching attempts are based on the order of declaration of the handlers.
Example-
Output
Catch New Exceptions
You can define your own exceptions by inheriting and overriding exception class functionality. Following is the example, which shows how you can use std::exception class to implement your own exception in standard way –
Output