x

C++ Exception Handling

PREV     NEXT

C++ Exception Handling:


What is Exception Handling?

  • An exception is an error that arises during the execution of a program. In C++, the exception is an event which is occurred at the runtime.
  • The exceptions are derived from std::exception class. It is a runtime error which can be handled and if they are not handled then the exception prints exception message and terminate the program.
  • In C++, the exception handling consists of three keywords: try, catch and throw.

Let us discuss them:

Try:

The try block identifies a block of code which can throw the exception. There can be one or more catch blocks after a try block.

Catch:

The catch block identifies the block of code that is executed when a particular exception is thrown. The program catches the exception with an exception handler at the place in a program where you want to handle the problem.

Throw:

It is used to throw an exception and it is also used to show those exceptions that a function throws which cannot be handled by them.

Let us have a look at the syntax:

try {

   // protected code

} catch( ExceptionName e1 ) {

   // catch block

} catch( ExceptionName e2 ) {

   // catch block

} catch( ExceptionName eN ) {

   // catch block

}


Let us have a look at the example:

What is the advantage of using Exception?

  • It helps programmers to create reliable systems.
  • Functions can handle only the exceptions they choose i.e., a function can throw many exceptions, but may choose handle only some of them.
  • We can handle the exceptions outside the regular code by throwing the exceptions from a function definition or by re-throwing an exception.
  • It helps to separate the exception handling code from the main logic of program.

Standard Exceptions in C++

In C++, it provides a list of standard exceptions which are defined in <exception> which we can use in our programs and they are arranged in a parent-child class hierarchy.