Home >Backend Development >C++ >How to handle multiple exceptions in C++?
C++ Ways to handle multiple exceptions include using try-catch blocks, which allow exceptions to be caught and handled for specific exception types; or using try blocks and a catch (...) block to catch all exception types. In the actual case, the try block attempts the division operation, captures the invalid_argument and exception exception types through two catch blocks, and outputs the corresponding error information.
C++ provides a variety of methods for handling multiple exceptions, including:
try-catch block
try { // 代码可能引发异常 } catch (const std::exception& e) { // 处理 std::exception 异常 } catch (const std::runtime_error& e) { // 处理 std::runtime_error 异常 }
catch(...)
try { // 代码可能引发异常 } catch (...) { // 处理所有异常 }
typeid
try { // 代码可能引发异常 } catch (const std::exception& e) { if (typeid(e) == typeid(std::runtime_error)) { // 处理 std::runtime_error 异常 } }
The following example demonstrates the use of a try-catch block to handle multiple exceptions:
#include <iostream> #include <exception> using namespace std; int main() { try { int x = 10; int y = 0; cout << "x / y = " << x / y << endl; } catch (const invalid_argument& e) { cout << "Division by zero error: " << e.what() << endl; } catch (const exception& e) { cout << "Error: " << e.what() << endl; } return 0; }
In this example:
try
block Attempt to execute code that may throw an exception. catch (const invalid_argument& e)
Block handles invalid_argument
exceptions. catch (const exception& e)
block handles all other exceptions. Running this program will output the following results:
Division by zero error: invalid argument
The above is the detailed content of How to handle multiple exceptions in C++?. For more information, please follow other related articles on the PHP Chinese website!