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

How to handle function exceptions in C++?

WBOY
Release: 2024-04-12 21:06:02
Original
760 people have browsed it

Exception handling is a mechanism in C for handling runtime errors. Throw exceptions with throw and catch and handle them with try, catch, and finally blocks. The specific syntax is as follows: try { // Code that may cause exceptions}catch (const std::exception& e) { // Catch and handle exceptions}catch(...) { // Catch all exceptions}

C++ 中如何处理函数异常?

How to handle function exceptions in C

Exception handling is a mechanism in C to handle runtime errors. Use the throw keyword to throw exceptions, and use try, catch, and optionally finally blocks to catch and handle exceptions.

Syntax:

try {
  // 可能引发异常的代码
} catch (const std::exception& e) {
  // 捕获并处理异常
} catch(...) {
  // 捕获所有异常
}
Copy after login

Practical example:

Consider the following function, which converts a string to an integer:

int string_to_int(std::string str) {
  try {
    int num = std::stoi(str);
    return num;
  } catch (const std::invalid_argument& e) {
    std::cout << "无法将字符串转换为整数" << std::endl;
    return -1;
  } catch (const std::out_of_range& e) {
    std::cout << "整数超出范围" << std::endl;
    return -1;
  }
}
Copy after login

Use this function in the main function:

int main() {
  std::string input = "123";
  int num;

  try {
    num = string_to_int(input);
    std::cout << num << std::endl;
  } catch (const std::exception& e) {
    std::cout << "出现异常: " << e.what() << std::endl;
  }

  return 0;
}
Copy after login

Advantages:

  • Improve program robustness
  • Allow Handle specific exceptions at specific locations
  • Provide error information and custom error handling
  • Prevent unexpected program termination

The above is the detailed content of How to handle function 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