Home  >  Article  >  Backend Development  >  How to handle multiple exceptions in C++?

How to handle multiple exceptions in C++?

WBOY
WBOYOriginal
2024-06-06 13:10:58730browse

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.

How to handle multiple exceptions in C++?

How to handle multiple exceptions in C++

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 异常
  }
}

Actual combat Case

The following example demonstrates the use of a try-catch block to handle multiple exceptions:

#include 
#include 

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn