C++

How to catch every exception in a C++ program2 min read

While writing programs if the programmer doesn’t know what kind of exception the program might raise, the catch all block can be used. It is used to catch any kind of exception. Syntax of catch all block is as follows:

While writing multiple catch statements care should be taken such that a catch all block should be written as a last block in the catch block sequence. If it is written first in the sequence, other catch blocks will never be executed. Following program demonstrates catch all block:




Input and output for the above program is as follows:

Rethrowing an Exception

In C++ if a function or a nested try-block does not want to handle an exception, it can rethrow that exception to the function or the outer try-block to handle that exception. Syntax for rethrowing and exception is as follows:

throw;

Following program demonstrates rethrowing and exception to outer try-catch block:

Input and output for the above program is as follows:

In the above program we can see that the exception is raised in the inner try block. The catch all block catches the exception and is rethrowing it to the outer try-catch block where it got handled.

Take your time to comment on this article.

Leave a Comment