异常捕获机制,c++
Exception catching mechanism, C++
考虑以下代码:
int main()
{
try
{
throw std::range_error("");
}
catch (std::bad_alloc)
{
std::cout << "AAAA" << std::endl;
throw;
}
catch (std::range_error)
{
std::cout << "BBB" << std::endl;
throw;
}
catch (std::exception)
{
std::cout << "CCC" << std::endl;
}
std::cout << "DDD" << std::endl;
}
这里我抛出一个类型为std::range_error
的异常,并试图捕获它。
逻辑上,第一个catch
块不能捕获它,因为类型不匹配(std::bad_alloc
和std::range_error
)。
第二个catch块必须捕获它,因为它们是std::range_error
的相同类型。
而且,当我在第二个catch块中重新抛出异常时,它必须在第三个catch块中被捕获。
BBB
CCC
DDD
但我只得到BBB
输出与终止。
当您re- throw
一个异常时,您将它完全抛出当前异常处理块....的上下文中
try
{
throw std::range_error("");
}
catch (std::bad_alloc)
{
std::cout << "AAAA" << std::endl;
throw;
}
catch (std::range_error)
{
std::cout << "BBB" << std::endl;
throw;
}
catch (std::exception)
{
std::cout << "CCC" << std::endl;
}
是一个异常处理块。因此,在遇到catch
块中的第一个throw
时,它离开整个块,在当前作用域之外寻找另一个处理块(try-catch)。如果没有找到,程序终止。
请参见c++中的try-catch
块
按您最初的想法打印…Live On Coliru…
int main()
{
try{
try{
try{
throw std::range_error("");
}
catch (std::bad_alloc) {
std::cout << "AAAA" << std::endl;
throw;
}
}
catch (std::range_error) {
std::cout << "BBB" << std::endl;
throw;
}
}
catch (std::exception){
std::cout << "CCC" << std::endl;
}
std::cout << "DDD" << std::endl;
}
打印:
BBB
CCC
DDD
记录:请避免在生产代码中使用简单的if-else
梯子可以完成的控制流使用异常
要重新捕获range_error,需要新的外部try catch块。
#include <iostream>
int main()
{
//outer try catch ------------------------
try {
// inner try catch ---------------------
try
{
throw std::range_error("");
}
catch (std::bad_alloc)
{
std::cout << "AAAA" << std::endl;
throw;
}
catch (std::range_error)
{
std::cout << "BBB" << std::endl;
throw;
}
// -------------------------------
}
catch (std::exception)
{
std::cout << "CCC" << std::endl;
}
// --------------------------------
std::cout << "DDD" << std::endl;
}
输出BBB
CCC
DDD
This throw
:
catch (std::range_error)
{
std::cout << "BBB" << std::endl;
throw; // <== this one
}
本身并不在try
的主体内,因此异常处理机制将每次持续走出一个作用域,直到找到一个为止。由于没有其他外部try
,因此根本不会捕获异常。
异常处理中没有重入口。
相关文章:
- 使用共享指针时,从共享指针本身释放内存的机制是什么
- 为什么 boost::comb 对结构化绑定的支持缺少结构化绑定机制对 boost::tuples::cons 的适应?
- 了解使用堆栈实现队列的递归调用机制
- 更好的事件处理机制?
- C++活动异常机制背后的推理
- 在信号槽机制与传统环路之间做出决定
- 虚拟继承的内部机制
- 任何类型的缓存机制
- C++20 中协程的机制是什么
- C++ 中的纯虚函数机制如何公开来自 DLL 的函数
- 派生类中函数参数变化的虚函数按常量类型在"function parameter"会破坏虚拟机制吗?
- 假想的锁定机制:非阻滞写,阅读和无效
- 将 boost::时序机制包装成类编译错误?
- 来自文本字符串或某种其他机制的代码类自动生成器
- 如何在 OpenCL 中使用缓冲区分配和映射内存机制
- 为什么std :: map中有一个分类机制
- 是我的等待 - 使用std :: mutex通知机制正确
- 使用C 17处理Unicode的有效,符合标准的机制是什么
- 带缓冲区的 iostream 的机制是什么?
- C++中"机械臂"的机制是什么?