Exception Handling in C++
Exception handling in C++ is a mechanism to handle runtime errors in a way that maintains normal program flow. In C++, exceptions are used to handle errors or other exceptional conditions in a program without disrupting the program’s execution.
C++ provides three key components for exception handling:
tryblock – Code that may throw an exception is placed inside thetryblock.throwkeyword – An exception is thrown using thethrowkeyword.catchblock – Exceptions thrown from thetryblock are handled by thecatchblock.
Here is a simple example:
Basic Syntax:
| #include <iostream> #include <stdexcept> // For standard exceptions int main() { if (y == 0) { int result = x / y; // This line will not execute due to the exception } catch (const std::invalid_argument &e) { return 0; |
Explanation:
-
tryblock: The code inside thetryblock attempts to perform a division. If a division by zero occurs, an exception is thrown usingthrow. -
throw: Thethrowstatement creates an exception object. In this case, we throw anstd::invalid_argumentexception with a message that division by zero occurred. -
catchblock: Thecatchblock handles the exception thrown in thetryblock. It catches exceptions of typestd::invalid_argumentand prints the error message using thewhat()method.
Exception Handling Flow:
- If an exception is thrown, the normal flow of control is interrupted, and the program jumps to the corresponding
catchblock. - If no exception occurs, the
catchblock is skipped, and the program continues executing after thetry-catchblock.
Multiple catch blocks:
You can have multiple catch blocks to handle different types of exceptions:
| #include <iostream> #include <stdexcept> int main() { if (y == 0) { int result = x / y; } catch (const std::runtime_error &e) { return 0; |
Explanation:
- The first
catchblock handles exceptions of typestd::runtime_error. - The second
catchblock is a more general catch that handles any other exceptions derived fromstd::exception.
Standard Exception Classes:
C++ provides several standard exception classes, which are part of the std namespace:
std::exception: The base class for all standard exceptions.std::runtime_error: Represents errors that are detected during runtime.std::logic_error: Represents errors in program logic (e.g., invalid arguments).std::overflow_error,std::underflow_error: For overflow or underflow conditions.std::bad_alloc: Thrown when memory allocation fails.
Re-throwing Exceptions:
You can re-throw an exception from a catch block if you want it to be handled further up the call stack:
| try { // Some code that might throw } catch (…) { // Handle exception, then rethrow it throw; // Re-throws the current exception } |
Conclusion:
Exception handling in C++ allows you to handle errors gracefully by catching exceptions and ensuring the program continues running smoothly. By using try, throw, and catch, you can manage errors more effectively and write more robust programs.