C++ Exception Handling: Try-Catch Guide
In C++, the try-catch statement block can be used to handle exceptions. The try block contains the code that may cause an exception, and the catch block is used to catch and handle the exception. Here is a simple example:
try {
// 可能引发异常的代码
throw std::runtime_error("An error occurred");
} catch (const std::exception& e) {
std::cout << "Exception caught: " << e.what() << std::endl;
}
In this example, the code in the try block throws a std::runtime_error exception, which is caught and handled by the catch block, printing out the error message of the exception.
In addition to using a catch block to catch exceptions, you can also use more advanced exception handling mechanisms such as std::exception_ptr or std::uncaught_exception. Additionally, you can create custom exception classes to represent different exceptional situations, and implement these classes by inheriting from std::exception.