2022-05-25 06:09:11
在C++中,异常处理机制允许程序在运行时捕获和处理异常情况,避免程序意外中断。以下是关于在C++函数中捕获和处理异常的详细说明:
1. 异常处理的基本语法C++通过try、catch和throw关键字实现异常处理:
通过指定异常类型(如runtime_error、invalid_argument等),可以针对性地处理特定错误。
示例:除法错误处理#include <iostream>#include <stdexcept>using namespace std;void divide(int a, int b) { try { if (b == 0) { throw runtime_error("除数不能为零"); } cout << "结果:" << a / b << endl; } catch (runtime_error& e) { cout << "异常:" << e.what() << endl; }}int main() { divide(10, 2); // 正常执行 divide(10, 0); // 捕获异常并输出错误信息 return 0;}使用catch(...)可以捕获任何未明确处理的异常,适用于通用错误处理。
示例:文件读取错误处理#include <iostream>#include <fstream>#include <stdexcept>using namespace std;void readFile(string filename) { try { ifstream file(filename); if (!file.is_open()) { throw invalid_argument("无法打开文件:" + filename); } // 其他文件读取操作 } catch (invalid_argument& e) { cout << "异常:" << e.what() << endl; } catch (...) { cout << "未知异常发生" << endl; }}int main() { readFile("test.txt"); // 文件存在时正常执行 readFile("nonexistent.txt"); // 捕获异常并输出错误信息 return 0;}可通过继承std::exception创建自定义异常类型,提供更具体的错误信息。
#include <exception>#include <string>class FileError : public exception {private: string message;public: FileError(const string& msg) : message(msg) {} const char* what() const noexcept override { return message.c_str(); }};void readFile(string filename) { try { ifstream file(filename); if (!file) throw FileError("自定义文件错误:" + filename); } catch (FileError& e) { cerr << e.what() << endl; }}总结C++的异常处理机制通过try-catch块实现,允许程序优雅地处理运行时错误。关键点包括:
通过合理使用异常处理,可以提升程序的健壮性和可维护性。