c++ - 在 C++ 中发生任何异常时运行通用代码
问题描述
我看起来类似于finally
c++ 但我遇到了RAII。不过,我有一点困惑。如果我有一些通用代码我想在出现任何异常的情况下运行,
例子: std::cout << "exception occured" << std::endl;
有没有办法做到这一点而不是复制相同的代码?
#include <iostream>
int main()
{
bool firstException = false;
try
{
if(firstException)
throw std::invalid_argument("the truth is out there!!");
else
throw std::domain_error("Bazzinga");
}
catch (std::invalid_argument const& e)
{
std::cout << e.what() << std::endl;
std::cout << "exception occured" << std::endl;
}
catch (std::domain_error const& e)
{
std::cout << e.what() << std::endl;
std::cout << "exception occured" << std::endl;
}
}
解决方案
我现在明白了molbdnilo在评论中所说的内容。下面的代码有答案。:) :D
#include <iostream>
int main()
{
bool firstException = true;
try
{
if(firstException)
throw std::invalid_argument("the truth is out there!!");
else
throw std::invalid_argument("Bazzinga");
}
catch (std::exception const& e)
{
std::cout << e.what() << std::endl;
std::cout << "exception occured" << std::endl;
}
}
推荐阅读
- node.js - 如何使用 NodeJs 在 https://api.linkedin.com/mediaUpload/ 上放置媒体
- rust - 在 for 迭代器中调用可变方法的不同方法
- java - TextView 不会显示 Html
- swift - 如何在 swift 中创建具有非常量变量的方法
- python - 防止 MySQL 在从 Python 导入数据时将浮点数/小数转换为 int
- typescript - 用于解析器 GraphQL 瑜伽的 TypeScript 类型(在上下文中使用 prisma2)
- mysql - 当我尝试访问或创建表时出现错误
- javascript - JavaScript 中被视为对象的函数
- java - 如何加快运行时 Java 代码检测?
- sql - 从字符串转换日期和/或时间时,面临转换失败等存储过程相关问题