输出异常
C++异常处理是一种用于在程序执行期间捕获和处理错误的机制。当发生异常时,程序将跳转到与该异常匹配的catch块,并执行指定的代码来处理该异常。C++中的异常处理分为三个步骤:
- 抛出异常:当程序发生错误时,可以使用throw语句抛出一个异常对象。例如:
throw std::runtime_error("An error occurred.");
这里抛出了一个std::runtime_error类型的异常对象,并传递了一个字符串作为错误消息。、
捕获异常
-
捕获异常:在try块中编写可能会引发异常的代码,并使用catch块来捕获并处理这些异常。例如:
try { // code that may throw exceptions } catch (const std::exception& e) { // handle exception of type std::exception }
这里使用了一个try块来包含可能会引发异常的代码,然后使用一个catch块来捕获std::exception类型的异常,并对其进行处理。
处理和恢复
- 处理和恢复:一旦捕获到了一个异常,就可以在catch块中编写特定于该类型的代码来处理它。例如:
try {
// code that may throw exceptions
}
catch (const std::runtime_error& e) {
std::cerr << "Runtime error: " << e.what() << '\n';
}
catch (...) {
std::cerr << "Unknown exception caught\n";
}
这里有两个不同类型的catch块:第一个处理std::runtime_error类型的异常,并打印出错误消息;第二个处理所有其他类型的异常,并打印出一个通用错误消息。
总之,C++异常处理提供了一种强大的机制来捕获和处理程序运行时可能遇到的各种错误情况。它可以帮助我们更好地控制程序的执行流程并提高程序的健壮性。
标准的异常
异常重载
您可以通过继承和重载 exception 类来定义新的异常。下面的实例演示了如何使用 std::exception 类来实现自己的异常:
struct MyException : public exception
{
const char * what () const throw ()
{
return "C++ Exception";
}
};
捕获不同错误
- 在C++中,可以使用多个catch块来捕获不同类型的异常。例如:
try {
// code that may throw exceptions
}
catch (const std::exception& e) {
// handle exception of type std::exception
}
catch (const std::runtime_error& e) {
// handle exception of type std::runtime_error
}
catch (...) {
// handle all other types of exceptions
}
在这个例子中,第一个catch块处理std::exception类型的异常,第二个catch块处理std::runtime_error类型的异常,最后一个catch块处理所有其他类型的异常。注意,最后一个catch块必须放在所有其他catch块之后。
另外,也可以使用逗号分隔符来捕获多个异常类型:
try {
// code that may throw exceptions
}
catch (const std::exception& e) {
// handle exception of type std::exception or its derived classes
}
catch (const std::runtime_error& e) , (const std::logic_error& e2) {
// handle exception of type std::runtime_error or std::logic_error
}
catch (...) {
// handle all other types of exceptions
}
在这个例子中,第二个catch块使用逗号分隔符同时捕获std::runtime_error和std::logic_error类型的异常。