Try-catch blocks are fundamental to exception handling in C++. They provide a structured way to handle runtime errors and unexpected situations in your code.
A try-catch block consists of two main parts:
try
block: Contains code that might throw an exceptioncatch
block: Handles the exception if one is thrown
try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
}
You can have multiple catch
blocks to handle different types of exceptions. This allows for more specific error handling based on the exception type.
Here's a simple example demonstrating how to use try-catch blocks to handle a division by zero error:
#include <iostream>
#include <stdexcept>
int main() {
int numerator = 10;
int denominator = 0;
try {
if (denominator == 0) {
throw std::runtime_error("Division by zero!");
}
int result = numerator / denominator;
std::cout << "Result: " << result << std::endl;
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}
You can use multiple catch blocks to handle different types of exceptions:
try {
// Code that might throw different types of exceptions
} catch (const std::runtime_error& e) {
// Handle runtime errors
} catch (const std::logic_error& e) {
// Handle logic errors
} catch (...) {
// Catch-all for any other exceptions
}
To fully understand exception handling in C++, you should also explore:
Try-catch blocks are essential for robust error handling in C++. They help create more reliable and maintainable code by providing a structured way to deal with exceptional situations.