Exceptions - Syntax


Exceptions provide a mechanism for transferring control of program execution from the point at which the exception is thrown to the point at which the exception is handled. Often exceptions are used to handle errors, although this need not be the case.

Syntax

try_block:
       try compound statement handler_list
 
handler_list:
       handler handler_list

handler:
       catch (exception_declaration) compound statement
 
exception_declaration:
       type_specifier_list declarator
       type_specifier_list abstract_declarator
       type_specifier_list
       ...
 
throw_expression:
       throw expression ;

Notes

Example

The following example declares a simple exception class and demonstrates the throwing and catching of exceptions.

class exception
{
 public:
  unsigned error;      // Error Code.
  string description;  // String based description of error.
 
  exception(unsigned value, const char* string) : error(value), description(string) {}
};
 
void f(int i) {if (i<0) throw exception(10,"Negative Value");}
 
void main()
{
 try
  {f(-1);}                                              // Causes exception to be thrown.
 catch(exception& caught) {cout << caught.description;} // Handler for class exception.
}