2013-03-22 235 views
2

当在C++中使用异常时,我注意到一个奇怪的行为,我希望这里有人能解释。看看下面的代码:异常抛出异常

class Foo 
{ 
public: 

    Foo() 
    { 
     throw 0; 
    } 
}; 

class RandomException 
{ 
public: 

    Foo f; 
}; 

void bar() 
{ 
    throw RandomException(); 
} 

// Case #1 
int main() 
{ 
    bar(); 
    return 0; 
} 

在上面的情况下,我有一个未处理的异常。现在,如果我改变main功能的身体:

// Case #2 
int main() 
{ 
    try 
    { 
     bar(); 
    } 
    catch (int) 
    { 
    } 

    return 0; 
} 

我吞咽异常。没有未处理的异常,代码运行良好。如果我的代码更改为:

// Case #3 
int main() 
{ 
    try 
    { 
     bar(); 
    } 
    catch (RandomException&) 
    { 
    } 

    return 0; 
} 

现在我再次有未处理的异常。

我想知道为什么在案件案例#2我没有未处理的异常,并在案例#3我这样做,即使在这两种情况下,我抛出两种例外,一个intRandomException类型之一。

C++如何在抛出异常时抛出异常时处理事件?

+1

你为什么会抛出一个自定义异常类的异常_inside_?这太疯狂了。 RandomException的构造函数调用了Foo的构造函数,并且只在case 2中捕获该异常,而不是case 3. – stefan 2013-03-22 13:16:54

+0

您最终在[The Daily WTF](http://thedailywtf.com/Articles/Crashception.aspx) 。 8v) – 2013-03-22 13:18:28

+0

@stefan科学当然。为什么呢? – Zeenobit 2013-03-22 13:19:19

回答

4

这里,RandomException对象的构造失败,出现异常,所以throw RandomException()从未完成和int(0)被抛出(在构建RandomException的处理)。

如果你有一个处理程序(如情况#2),控制权将被转移到该处理程序。如果不是(如情况#3),将调用std::terminate()

+0

因此,由于'RandomException'的构造永远不会“完成”,它永远不会被抛出? – Zeenobit 2013-03-22 13:20:54

+0

@Zeenobit:的确,这就是发生的事情。 – 2013-03-22 13:29:10