Introduction

An exception is a problem that arises during the execution of a program. A C++ exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero. Exceptions provide a way to transfer control from one part of a program to another. Exception handling mechanism consists of following parts:

  1. Find the problem (hit the exception)
  2. Inform about its occurrence (throw the exception)
  3. Receive error information (catch the exception)
  4. Take proper action (handle the exception)

C++ consists of below keywords for handling the exception

  • try: Try block consists of the code that may generate exception. Exception are thrown from inside the try block.
  • throw: Throw keyword is used to throw an exception encountered inside try block. After the exception is thrown, the control is transferred to catch block.
  • catch: Catch block catches the exception thrown by throw statement from try block. Then, exception are handled inside catch block.

 

Syntax

Multiple catch exception statements are used when a user wants to handle different exceptions differently. For this, a user must include catch statements with different declaration.

try
{
  body of try block
}
catch (type1 argument1)
{
  // Handle exception
}
catch (type2 argument2)
{
  // Handle exception
}
catch (type3 argument3)
{
  // Handle exception
}

Sometimes, it may not be possible to design a separate catch block for each kind of exception. In such cases, we can use a single catch statement that catches all kinds of exceptions.

catch (...)
{
  statements;
}

 

Example

#include <iostream>
#include<conio.h>
using namespace std;

int main()
{
  int x[3] = {-1,2};
  for(int i=0; i<2; i++)
  {
    int ex = x[i];
    try 
    {
      if (ex > 0)
          // Throw numeric value as exception
          throw ex;
      else
          // Throw a character as exception
          throw 'ex';
    }
    // Catch numeric exceptions
    catch (int ex)
    {
      cout << "Integer exception\n";
    }
    // Catch character/string exceptions
    catch (char ex)
    {
      cout << "Character exception\n";
    }
    // Generalised catch block
    catch(...)
    {
      cout << "Special exception\n";
    }
  }
}

 

Standard Exceptions

There are some standard exceptions in C++ under <exception> which we can use in our programs. They are arranged in a parent-child class hierarchy which is depicted below:

  • std::exception – Parent class of all the standard C++ exceptions.
  • logic_error – Exception happens in the internal logical of a program.domain_error – Exception due to use of invalid domain.
    • invalid argument – Exception due to invalid argument.
    • out_of_range – Exception due to out of range i.e. size requirement exceeds allocation.
    • length_error – Exception due to length error.
  • runtime_error – Exception happens during runtime.range_error – Exception due to range errors in internal computations.
    • overflow_error – Exception due to arithmetic overflow errors.
    • underflow_error – Exception due to arithmetic underflow errors
  • bad_alloc – Exception happens when memory allocation with new() fails.
  • bad_cast – Exception happens when dynamic cast fails.
  • bad_exception – Exception is specially designed to be listed in the dynamic-exception-specifier.
  • bad_typeid – Exception thrown by typeid.

 

Define New Exceptions

You can define your own exceptions by inheriting and overriding exception class functionality. Following is the example, which shows how you can use std::exception class to implement your own exception in standard way. what() is a public method provided by exception class and it has been overridden by all the child exception classes. This returns the cause of an exception.

#include <iostream>
#include <exception>
using namespace std;

struct MyException : public exception {
  const char * what () const throw () {
     return "C++ Exception";
  }
};

int main() {
  try {
     throw MyException();
  } catch(MyException& e) {
     std::cout << "MyException caught" << std::endl;
     std::cout << e.what() << std::endl;
  } catch(std::exception& e) {
     //Other errors
  }
}

// Console Output
MyException caught
C++ Exception