C++ Exception Handling

tutorial and example
tutorial and example

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, concept of exception handling is applied.

Exception handling handles the exception occur and transfer the program control to other part of program. Exception handling is use to detect and report an exception, so that an appropriate action can be taken.

Exception handling follows the following steps to handle 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 exception. These are:

  1. try
  2. throw
  3. catch

try: try block identify the code which generate 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 try block.


C++ Exception Handling Example 1



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