在catch块中抛出的异常会被后面的catch块捕获吗?
Will exception thrown in catch block be caught by later catch blocks?
考虑以下c++代码:
try {
throw foo(1);
} catch (foo &err) {
throw bar(2);
} catch (bar &err) {
// Will throw of bar(2) be caught here?
}
我希望答案是否定的,因为它不在try
块内,我在另一个问题中看到Java的答案是否定的,但我想确认c++也是否定的。是的,我可以运行一个测试程序,但我想知道在远程情况下,我的编译器有一个错误的行为的语言定义。
No。只有在相关的try
块中抛出的异常才能被catch
块捕获。
不,它不会,在层次结构之上的封闭catch块将能够捕获它。
样本的例子:void doSomething()
{
try
{
throw foo(1);
}
catch (foo &err)
{
throw bar(2);
}
catch (bar &err)
{
// Will throw of bar(2) be caught here?
// NO It cannot & wont
}
}
int main()
{
try
{
doSomething();
}
catch(...)
{
//Catches the throw from catch handler in doSomething()
}
return 0;
}
不,catch块处理最近的异常,所以如果你尝试…catch (Exception &exc)…catch (SomethingDerived &derivedExc)异常将在&exc块中处理
您可以通过将异常委托给调用方法
相关文章:
- 有没有更好的方法来处理异常? try-catch块真的很丑
- std::unique_ptr 在 try-catch 块中未捕获取消引用异常
- 如果一个对象是在本地创建的,并在C++中作为异常抛出,那么本地对象如何在其范围之外有效,即在 catch 块中?
- 构造函数中的异常:init() 方法、指针、大型 try/catch 或
- 指定特定异常以使用 catch 停止 GDB
- 无法使用 C++ catch(..) 捕获访问冲突异常
- 具有两个类似catch部分的代码的异常处理行为
- 基类catch不捕获异常,即使它出现在派生类catch之前
- 为什么当我抛出派生类的对象时,基类的 catch 块会捕获异常
- C++ 异常中的 catch(异常)是什么意思?
- 格式化文件异常被 try catch 块忽略
- 从catch块调用异常类中的函数并不是打印从try块传递的值
- 从用catch(..)捕获的异常中获取一些信息
- "try catch(...)"可以在 C++ 中捕获哪些异常?
- MFC TRY CATCH与C++对MFC异常的尝试捕获
- 使用try-Catch异常处理程序和if-else条件检查之间的区别
- catch站点中异常的常见用法是什么
- catch语句如何在没有反射的情况下识别异常类型
- 如何在这个try-show-catch代码中对异常进行排序
- 如何使用ApacheThrift在单个catch语句中捕获所有自定义异常