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:
try
block – Code that may throw an exception is placed inside thetry
block.throw
keyword – An exception is thrown using thethrow
keyword.catch
block – Exceptions thrown from thetry
block are handled by thecatch
block.
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:
-
try
block: The code inside thetry
block attempts to perform a division. If a division by zero occurs, an exception is thrown usingthrow
. -
throw
: Thethrow
statement creates an exception object. In this case, we throw anstd::invalid_argument
exception with a message that division by zero occurred. -
catch
block: Thecatch
block handles the exception thrown in thetry
block. It catches exceptions of typestd::invalid_argument
and 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
catch
block. - If no exception occurs, the
catch
block is skipped, and the program continues executing after thetry-catch
block.
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
catch
block handles exceptions of typestd::runtime_error
. - The second
catch
block 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.