c++++ 中捕获特定类型异常的方法:使用 try-catch 块。在 catch 子句中指定要捕获的异常类型,如 catch (const std::runtime_error& e)。实战案例中,read_file() 函数通过抛出 std::runtime_error 来处理文件不存在的情况,并使用 try-catch 块来捕获此异常并打印错误消息。

C++ 函数异常处理中捕获特定类型的异常
在 C++ 中,使用 try-catch 块处理函数中抛出的异常时,可以使用 catch 子句捕获特定类型的异常。例如,要捕获 std::runtime_error 类型的异常,可以使用以下语法:
try { // 函数代码} catch (const std::runtime_error& e) { // 处理 std::runtime_error 异常}
实战案例:
立即学习“C++免费学习笔记(深入)”;
假设有一个 read_file() 函数,它负责从文件中读取数据。如果文件不存在,函数会抛出一个 std::runtime_error 异常。我们可以使用 try-catch 块来处理此异常:
#include #include void read_file(const std::string& filename) { std::ifstream file(filename); if (!file.is_open()) { throw std::runtime_error("File not found"); } // 读取文件内容}int main() { try { read_file("myfile.txt"); } catch (const std::runtime_error& e) { std::cerr << "Error: " << e.what() << std::endl; } return 0;}
运行此程序,如果文件 “myfile.txt” 不存在,将打印以下错误消息:
Error: File not found
以上就是C++ 函数异常处理中如何捕获特定类型的异常?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1447144.html
微信扫一扫
支付宝扫一扫