C++ catch block
Created By: chatGPT
In C++, a catch block is used to handle exceptions that may be thrown in your code. It comes after a try block, which contains the code that might throw an exception. The basic syntax for defining a try-catch structure is as follows:
try {
// Code that might throw an exception
} catch (const ExceptionType &e) {
// Code to handle the exception
}
You can catch different types of exceptions by specifying the exception type in the catch block. This helps you handle specific errors appropriately. For example, if you have a function that may throw a division by zero error, you could do something like this:
void divide(int a, int b) {
if (b == 0) {
throw std::runtime_error("Division by zero");
}
std::cout << a / b;
}
int main() {
try {
divide(10, 0);
} catch (const std::runtime_error &e) {
std::cout << "Caught an exception: " << e.what() << std::endl;
}
}
You can also have multiple catch blocks to handle different exceptions. This allows for specific handling of various types of exceptions. Here's an example that illustrates this:
try {
throw std::out_of_range("Out of range error");
} catch (const std::out_of_range &e) {
std::cout << "Caught an out_of_range exception: " << e.what() << std::endl;
} catch (const std::exception &e) {
std::cout << "Caught a general exception: " << e.what() << std::endl;
}
In addition to handling exceptions, you can also use a catch-all block to catch any exception that is derived from the standard
std::exception
. This is done by catching the base class type. It's often a good practice to include this as a final catch block:try {
throw std::bad_alloc();
} catch (const std::bad_alloc &e) {
std::cout << "Caught a bad_alloc exception: " << e.what() << std::endl;
} catch (...) {
std::cout << "Caught an unknown exception" << std::endl;
}