C++ Exception Handling

C++ Exception Handling refers to three keywords: try, catch and throw. While programming in C++, there often comes scenarios when compiler shows error. Errors occur when there is some problem in the code and it cannot be compiled. There can be of different types such as:

  • Syntax error
  • Wrong input error
  • Error made by programmer in coding
  • Undefined response

C++ Exceptions

An exception is an issue that occurs during the execution of a program for example, anything divided by zero arises an exception. The response to such undefined conditions when program is running is a C++ exception. When program encounters an exception it stops running and generates an error message. In technical terms it is referred to as C++ will throw an exception or C++ will throw an error.

The three keywords that perform C++ exceptional handling are:

try:try is a block of code that checks for errors in the code while its execution. It is followed by catch block.

catch: When an exception occurs, the piece of code in the block catch is executed. The try and catch blocks work in pair. Programmer can implement more than one catch blocks.

throw: As clear from the keyword itself, the throw block throws an exception when it finds an error. Programmer can define his/her own custom error messages using throw.

The syntax for using try catch and throw blocks in code is:

Consider the following example to understand the concept of C++ exception handling.

In the below code, the program checks if temperature is moderate for storage or not. The moderate temperature is equal to or below 30 degree centigrade. In try block, the program checks if the storage temperature condition is satisfied. If it is satisfied then it prints “Temperature is moderate for storage.”. And if it is greater than 30 degrees, it throws an exception. That exception is handled in the catch block.

#include <iostream>
using namespace std;
int main() {
  try {
    int temp = 19;
    if (temp <= 30) {
      cout << "Temperature is moderate for storage.";
    } else {
      throw (temp);
    }
  }
  catch (int num) {
    cout << "Please store at a temperature below 30 degrees" << endl;
    cout << "The current temperature in degree centigrade is: " << num;  
  }
  return 0;
}

Since now temperature is smaller than 30 degrees, so catch block does not execute. The output of the above code after compilation is;

For example, if temperature is greater than 30 degrees.

int temp = 31;

The output of the above code will be:

Undefined Exception

When the type of throw is not known, programmer can use catch(…) phrase with three dots (…) to handle it.

#include <iostream>
using namespace std;
int main() {
  try {
    int temp = 31;
    if (temp <= 30) {
      cout << "Temperature is moderate for storage.";
    } else {
      throw (temp);
    }
  }
  catch (...) {
    cout << "Please store at a temperature below 30 degrees" << endl;
  } 
  return 0;
}

The output of above code after compilation is:

C++ Predefined Exceptions

C++ <exception> library defines some standard std::exceptions. The name and description of these exception is shown in the table below.

Sr.#ExceptionDescription
1exceptionIts the main exception and is the main class of standard C++ exceptions.
2bad_allocIt is thrown as an exception when there is error in making storage for new.
3bad_castIt occurs when dynamic_cast gives an error on run time.
4bad_exceptionIt is thrown by C++ in run time when unexpected errors occur.
5bad_typeidIt is useful to handle exceptions in typeid.
6logic_errorIt is thrown when there is an error in program’s logic.
7domain_errorThis exception is thrown when out of domain input is used like mathematically invalid domain.
8invalid_argumentIt occurs when an invalid argument is passed to a function.
9length_errorThis exception is thrown when length of any string object exceeds the defined limit of length.
10out_of_rangeIt occurs when and object out of the defined range is accessed. For example, elements of an array.
11runtime_errorIt occurs when there is a failure beyond the scope of program.
12overflow_errorThis exception is thrown to cover arithmetic overflow errors. For example, when result of a mathematic operation is too large for it destination.
13range_errorIt occurs when the result is stored in a wrong (out of range) destination.
14underflow_errorIt is thrown in the case of arithmetic underflow errors.
Standard std:exceptions