如何处理异常引发异常:使用 throw 关键字引发异常。处理异常:使用 try-catch 块来处理异常。标准异常类:使用内置的异常类,如 std::runtime_error 和 std::logic_error。自定义异常类:创建自己的异常类,继承自 std::exception。实践案例:在文件操作、数据库访问和其他可能出现错误的情形中使用异常处理。
如何在 C++ 中使用框架处理异常
异常处理是一种处理程序中未预料的错误或异常情况的方法。在 C++ 中,异常通过关键字 throw
引发,并通过 try-catch
块处理。
标准异常类
C++ 标准库提供了几个内置异常类,如:
std::runtime_error
:表示运行时错误。std::logic_error
:表示逻辑错误。std::range_error
:表示索引超出范围。自定义异常类
你还可以创建自己的自定义异常类。下面是一个示例:
class MyException : public std::exception { public: MyException(const char* message) : message_(message) {} const char* what() const noexcept override { return message_.c_str(); } private: std::string message_; };
示例
下面是一个演示如何在 C++ 程序中使用异常处理的示例:
#include <iostream> using namespace std; int main() { try { // 可能会引发异常的代码 int x = 0; int y = 1 / x; // 尝试除以零 cout << "结果:" << y << endl; } catch (const std::exception& e) { // 处理异常 cout << "捕获异常:" << e.what() << endl; } return 0; }
实践案例
在文件操作中,异常处理非常有用。以下是如何在文件打开失败时使用异常处理的示例:
#include <fstream> using namespace std; int main() { try { // 打开文件 ifstream file("input.txt"); // 检查文件是否打开成功 if (!file.is_open()) { throw MyException("无法打开文件"); } // 从文件中读取数据 // ... // 关闭文件 file.close(); } catch (const MyException& e) { // 处理自定义异常 cout << "自定义异常:" << e.what() << endl; } catch (const std::exception& e) { // 处理其他异常 cout << "标准异常:" << e.what() << endl; } return 0; }