Using C++ Exceptions
tryA try block is a group of C++ statements, normally enclosed in braces { }, which may cause an exception. This grouping restricts exception handlers to exceptions generated within the try block. catchA catch block is a group of C++ statements that are used to handle a specific raised exception. Catch blocks, or handlers, should be placed after each try block. A catch block is specified by:
throwThe throw statement is used to throw an exception to a subsequent exception handler. A throw statement is specified with:
Example program for try-catch and throw When an exception is thrown, the runtime mechanism first searches for an appropriate handler in the current scope. If no such handler exists, control is transferred from the current scope to a higher block in the calling chain. This process is iterative: It continues until an appropriate handler has been found. At this point, the stack has been unwound and all the local objects that were constructed on the path from a try block to a throw expression have been destroyed. The stack unwinding process is very similar to a sequence of return statements, each returning the same object to its caller. Exception Type MatchThe type of an exception determines which handler will catch it. The matching rules for exceptions are more restrictive than the matching rules for function overloading. Consider the following example: try { throw int(); } catch (unsigned int) { } Passing Exception Objects to a Handler void Write(FILE *pf) Exception Type MatchThe type of an exception determines which handler will catch it. The matching rules for exceptions are more restrictive than the matching rules for function overloading. Consider the following example: try { throw int(); } // the following block won't catch the exception from // the previous try block catch (unsigned int) { The thrown exception is of type int, but the handler expects an unsigned int. The exception-handling mechanism doesn't consider these to be matching types; therefore, the thrown exception isn't caught. Exception SpecificationA function that might throw an exception can warn its users by specifying a list of the exceptions that it can throw. Exception specifications are particularly useful when users of a function can view its prototype but can't access its source file. Following is an example of specifying an exception: class Zerodivide{/*..*/}; int divide (int, int) throw |