C++:Exception Handling|try throw catch

The error handling code basically consists of two segments,

• one to detect errors and to throw exceptions and
• the other to catch exceptions and to take appropriate actions.

When writing programs we must always be on the lookout for places in the program where an exception could be generated.

Exception handling constructs

The exception handling mechanism transfers control and information from the point of exception in the program to an exception handler associated with the try block. An exception handler will be invoked only by a thrown exception in the code executed by the handlers in try block. C++ offers following three constructs for defining these blocks.

(1) try
(2) throw
(3) catch

try construct

The try keyword defines the boundary within which an exception can occur. Following the try keyword is a block of code enclosed by braces. This indicates that the program is prepared to test for the existence of an exception. If an exception occurs the program flow is interrupted and exception handler is invoked.

try
{
statements
}

throw construct

the keyword throw is used to raise an exception when an error is generated in the computations. The throw expression initializes a temporary object of the type T (to match the type of the arguments arg) used in the throw (T arg). The of the throw construct is

throw T;

catch construct

The exception handler is indicated by the catch keyword. It must be used immediately after the statement marked by the try keyword. The catch handler can also occur immediately after another catch. Each handler will only evaluate an exception that matches or can be converted to the type specified in its arguments list.

catch (T )
{
statements
}