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
- 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.
- 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 (...)
- 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++:
Output (when denominator is zero):
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 Class | Description |
---|---|
std::exception | Base class for all standard exceptions |
std::logic_error | Represents errors due to errors in the internal logic of the program |
std::runtime_error | Represents errors that can only be determined during runtime |
std::invalid_argument | Thrown when an argument with an invalid value is passed |
std::out_of_range | Thrown when an attempt is made to access an element outside the range of a data structure |
std::overflow_error | Represents arithmetic overflow errors |
std::underflow_error | Represents arithmetic underflow errors |
std::range_error | Thrown when a mathematical result is out of range |
Last updated on -