Home > Backend Development > C++ > body text

How to handle multiple exceptions in C++?

WBOY
Release: 2024-06-06 13:10:58
Original
837 people have browsed it

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 异常
}
Copy after login

catch(...)

try {
  // 代码可能引发异常
} catch (...) {
  // 处理所有异常
}
Copy after login

typeid

try {
  // 代码可能引发异常
} catch (const std::exception& e) {
  if (typeid(e) == typeid(std::runtime_error)) {
    // 处理 std::runtime_error 异常
  }
}
Copy after login

Actual combat Case

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;
}
Copy after login

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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!