Exception Handling In C++

Exception handling is a mechanism in C++ used to handle runtime errors and abnormal conditions that may occur during program execution. It allows you to gracefully handle errors without causing the program to crash. The core components of exception handling in C++ include:

  • try block
  • catch block
  • throw statement
  1. Try Block: A try block is used to enclose the code that may throw an exception. It is followed by one or more catch blocks.
  2. Catch Block: A catch block is used to handle exceptions thrown within the corresponding try block. It specifies the type of exception it can handle. Multiple Catch Blocks: You can have multiple catch blocks to handle different types of exceptions within the same try block. The catch blocks are checked sequentially, and the first one that matches the thrown exception type is executed. The syntax for a catch-all block is catch (...)
  3. Throw Statement: The throw statement is used to explicitly throw an exception. It can throw any type of object, including built-in types, classes, or even pointers.

Here's a simple example demonstrating exception handling in C++:

#include <iostream>
using namespace std;
 
// Function to divide two numbers and handle division by zero exception
float divide(float numerator, float denominator) {
    if (denominator == 0)
        throw "Division by zero exception"; // Throw a const char* exception
    return numerator / denominator;
}
 
int main() {
    try {
        float result = divide(10, 0); // Attempt division by zero
        cout << "Result: " << result << endl;
    } catch (const char* error) { // Catch the exception thrown as a const char*
        cout << "Error: " << error << endl; // Print the error message
    } catch (...) { // Catch any other type of exception
        cout << "Caught unknown exception" << endl;
    }
   
    return 0;
}

Output (when denominator is zero):

Error: Division by zero exception

Explanation:

  • The divide function attempts to divide two numbers and throws a "Division by zero exception" if the denominator is zero.
  • In the main function, the division operation is performed inside a try block.
  • If an exception is thrown during the division, it is caught by the corresponding catch block, which handles the exception by printing the error message.

C++ Standard Exceptions

In C++, standard exceptions are predefined exception classes provided by the C++ Standard Library. These exceptions are designed to handle common error scenarios and are organized in a hierarchy, with the base class being std::exception. Each standard exception class inherits from std::exception and provides specific error information.

Here is the small description of each exception:

Exception ClassDescription
std::exceptionBase class for all standard exceptions
std::logic_errorRepresents errors due to errors in the internal logic of the program
std::runtime_errorRepresents errors that can only be determined during runtime
std::invalid_argumentThrown when an argument with an invalid value is passed
std::out_of_rangeThrown when an attempt is made to access an element outside the range of a data structure
std::overflow_errorRepresents arithmetic overflow errors
std::underflow_errorRepresents arithmetic underflow errors
std::range_errorThrown when a mathematical result is out of range
How's article quality?

Last updated on -

Page Contents