Exception Handling in C++ with Example

Exception Handling in C++:

In C++, Exceptions are of two types, these are:

1. Synchronous Exception – Errors such as “Out-of-range index” and “Over-flow” belong to the synchronous type exception.
2. Asynchronous Exception – The errors that are caused by events beyond the control of the program that is called Asynchronous Exception.

The purpose of the Exception Handling mechanism is to provide and detect a report of “exceptional circumstances” so that appropriate action can be taken. The mechanism suggests a separate error-handling code that performs the following tasks:

1. Find the exception
2. Throw the exception
3. Catch the exception
4. Handle the exception

Exception Handling Mechanism:

In C++, the exception handling mechanism is basically built upon three keywords namely:
1. Try
2. Throw
3. Catch

Exception Handling

Try: The keyword try is used to preface a block of statements that may generate an exception. This block of statements is known as the try block.

Throw: When an exception is detected, it is thrown using a throw statement in the try block.

Catch: The catch block catches an exception and must immediately follow the try block that throws the exception.

Syntax of Exception Handling:

.......
.......
try
{
statement; // generates an exception
throw exception; // throws an exception
.........
}
catch(Exception-type e)
{
statement; // processes the exception
}
........
........

Exception Specifications in C++:

It is possible to restrict a function to throw only certain specified exceptions. This is achieved by adding a throw list clause to the function definition. It has the following syntax:

type function(arg-list) throw (type-list)
{
.....
..... // function body
.....
}

The type list specifies the type of exceptions that may be thrown. Throwing any other type of exception will cause abnormal program termination. If we wish to prevent a function from throwing any exception.

Exception in Constructor:

What will happen if an exception is thrown while executing a constructor? Since the object is not yet fully constructed, if the constructor had reserved some memory before the exception was raised then there would be no mechanism to prevent such memory leak. Hence, an appropriate exception-handling mechanism must be implemented in the constructor to handle exceptions that occur during object construction.

If we allow the exception to be handled inside the main then we would not be able to prevent the memory leak situation. Thus, we must catch the exception within the constructor block so that we get the chance to free up any reserved memory space. However, we must simultaneously rethrow the exception to be appropriately handled inside the main block.

Example:

class test
{
public:
test()
{
try
{
data-type dt;
throw e;
}
catch(e)
{
delete dt;
throw e;
}
}
};