C++ Exception Handling

Exception is an unexpected problem that occurs at program run time. This problem might include condition such as division by zero, running out of memory space, array out of bonds, etc. To handle the exception occur during program execution, the concept of exception handling is applied.

Exception handling handles the exception occurs and transfer the program control to other parts of the program. Exception handling is used to detect and report an exception so that appropriate action can be taken.

Exception handling follows the following steps to handle the exception:

  1. Find the exception (Hit the exception)
  2. Inform about exception occurrence (Throw the exception)
  3. Receive exception information (Catch the exception)
  4. Take proper action (Handle the exception)

 

C++ exception handling mechanism uses three keywords to handle the exception. These are:

  1. try
  2. throw
  3. catch

try: try block identify the code which generates an exception.

throw: throw keyword used to throws an exception from inside the try block.

catch: catch block catches the exception thrown by throw keyword from the try block.

Syntax

C++ Exception Handling Example 1

Output:

The catch block is written just below the try block irrespective to the location of throw statement.

Leave a Comment