C++ Exceptions are a mechanism for handling unexpected events. Exceptions are caught through try blocks and handled using catch blocks. First, use the throw statement to throw an exception. The exception type can be a standard library exception class or a custom exception class. In a practical case, if the divider is zero, the divide function will throw a runtime_error, and the exception will be caught and handled through the catch block in the main function.
C++ exceptions are a mechanism for handling unexpected events. They allow programs to handle errors gracefully without causing crashes.
To catch exceptions, use the following syntax:
try { // 容易抛出异常的代码 } catch (exception& e) { // 异常处理代码 }
try
The block contains code that may throw exceptions. If an exception is thrown, control is transferred to the corresponding catch
block. catch
The block parameter specifies a reference used to handle a specific exception type.
You can throw an exception by using the throw
statement:
throw exception();
exception
can be a standard library exception class (such as runtime_error
) or a custom exception class.
Consider the following code example:
#include <exception> int divide(int a, int b) { if (b == 0) { throw std::runtime_error("除数不能为零"); } return a / b; } int main() { try { int result = divide(10, 0); std::cout << result << std::endl; } catch (const std::runtime_error& e) { std::cout << "错误:" << e.what() << std::endl; } }
In the main
function, we call the divide
function and try Catch any exceptions that may be thrown. If the divider is zero, the divide
function throws a runtime_error
and displays an error message.
The above is the detailed content of How to catch and handle C++ exceptions?. For more information, please follow other related articles on the PHP Chinese website!