How to handle exceptions in C++ using try and catch?
In C++, try and catch statements can be used to catch and handle exceptions. The try block surrounds the code that may throw an exception, while the catch block handles the caught exception.
Here is the general format of try and catch statements:
try {
// 可能会引发异常的代码
}
catch (ExceptionType1 e1) {
// 处理 ExceptionType1 类型的异常
}
catch (ExceptionType2 e2) {
// 处理 ExceptionType2 类型的异常
}
catch (...) {
// 处理其他类型的异常
}
In the try block, you can put code that may throw an exception. If an exception is thrown in the try block, the program will immediately jump to the catch block to handle the exception. The type of the catch block’s parameter specifies the type of exceptions it can catch. If the type of the thrown exception matches the parameter type of the catch block, that catch block will be executed. If the parameter type of the catch block is an ellipsis (…), it can catch exceptions of any type.
Multiple catch blocks can be used to handle different types of exceptions as needed. The catch blocks can be arranged in a specific sequence to first handle specific types of exceptions and then handle more generic types of exceptions. Within the catch block, code can be written to handle the exception, such as printing error messages or performing corrective actions.
Here is a simple example demonstrating the use of the try and catch statements:
#include <iostream>
int main() {
try {
int a = 10;
int b = 0;
int result = a / b;
}
catch (const std::exception& e) {
std::cout << "发生异常: " << e.what() << std::endl;
}
return 0;
}
In the code above, we performed a division operation in the try block with a divisor of 0, which will trigger an exception of type std::exception. The catch block caught the exception and printed the exception information.
It is important to note that try and catch statements are typically used to handle runtime exceptions, not syntax errors. In C++, you can use try and catch to catch exception types provided by the standard library, or you can create custom exception classes to implement your own exception handling mechanism.