Home > Backend Development > C++ > body text

How to catch and handle C++ exceptions?

WBOY
Release: 2024-06-05 22:33:59
Original
291 people have browsed it

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.

How to catch and handle C++ exceptions?

How to catch and handle C++ exceptions

C++ exceptions are a mechanism for handling unexpected events. They allow programs to handle errors gracefully without causing crashes.

Catching exceptions

To catch exceptions, use the following syntax:

try {
  // 容易抛出异常的代码
} catch (exception& e) {
  // 异常处理代码
}
Copy after login

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.

Throw exception

You can throw an exception by using the throw statement:

throw exception();
Copy after login

exception can be a standard library exception class (such as runtime_error) or a custom exception class.

Practical Case

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

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!

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