Even the best-written programs can encounter unexpected situations: a file might be missing, a network connection might fail, or a user might try to divide by zero.
If left unhandled, these runtime errors will cause the program to crash abruptly. Exception Handling provides a structured way to react to exceptional circumstances, transferring control from the point where the error occurred to a designated error handler.
C++ handles exceptions using three keywords:
try: You place the code that might generate an error inside a try block.throw: When a problem occurs, you use the throw keyword to generate an exception. You can throw primitive types (like int or string), or custom class objects.catch: The catch block intercepts the thrown exception and executes code to handle the error.#include <iostream>
#include <stdexcept>
using namespace std;
int main() {
double numerator = 10;
double denominator = 0;
try {
if (denominator == 0) {
// Error detected! Throw an exception.
throw runtime_error("Division by zero error!");
}
// This line is skipped if an exception is thrown
cout << "Result: " << (numerator / denominator) << endl;
} catch (const runtime_error& e) {
// This block catches the exception and handles it gracefully
A single try block can be followed by multiple catch blocks to handle different types of exceptions in different ways.
try {
// Code that might throw int, char*, or standard exceptions
} catch (int errorCode) {
cout << "Caught integer error: " << errorCode << endl;
} catch (const char* errorMsg) {
cout << "Caught string error: " << errorMsg << endl;
} catch (...) {
// The "catch-all" handler intercepts any exception not caught above
cout << "Caught an unknown exception!" << endl;
}C++ provides a standard library of exceptions under the <stdexcept> header. They all inherit from a base class called std::exception.
Common standard exceptions include:
std::runtime_error: Errors that can only be detected at runtime.std::out_of_range: Thrown when accessing elements out of bounds (e.g., in a vector).std::invalid_argument: Thrown when an invalid argument is passed to a function.try block.throw to signal an error condition.catch blocks to define how to handle specific errors.catch(...) block can be used to catch any unknown exception.An unexpected problem that arises during the execution of a program, disrupting the normal flow of instructions.
A block of code to be tested for errors while it is being executed.
A keyword used to signal that an error has occurred, throwing an exception to be caught.
A block of code that handles the exception thrown by the try block.
Test your understanding with 2 questions
What happens if an exception is thrown but no matching catch block is found?
How can you write a catch block that catches any type of exception?
2 Modules
2 Modules