【发布时间】:2010-04-26 20:48:29
【问题描述】:
如果由于异常导致堆栈展开期间析构函数在 C++ 中抛出,则程序终止。 (这就是为什么析构函数永远不应该在 C++ 中抛出。)示例:
struct Foo
{
~Foo()
{
throw 2; // whoops, already throwing 1 at this point, let's terminate!
}
};
int main()
{
Foo foo;
throw 1;
}
terminate called after throwing an instance of 'int'
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
如果在 Java 中由于相应的 try 块中的异常而进入 finally 块,并且该 finally 块抛出第二个异常,则第一个异常被静默吞下。示例:
public static void foo() throws Exception
{
try
{
throw new Exception("first");
}
finally
{
throw new Exception("second");
}
}
public static void main(String[] args)
{
try
{
foo();
}
catch (Exception e)
{
System.out.println(e.getMessage()); // prints "second"
}
}
我想到了这个问题:一种编程语言能否处理同时抛出的多个异常?那会有用吗?你有没有错过这个能力?有没有一种语言已经支持这个?有这种方法的经验吗?
有什么想法吗?
【问题讨论】:
-
你刚刚让我的大脑抛出异常
-
有趣的问题。我假设“处理异常”是指“由于异常而展开堆栈”,而不是“从 catch 块执行代码”。后者我称之为“处理异常”,但由于已找到处理程序,您可以从那里抛出异常(至少在 C++ 中)。
-
@Nick 你说得对,我编辑了标题。如果您知道更好的,请随时再次更改它;-)
-
finally 块总是在 try 块退出时执行。无论是否抛出异常,finally 块都会执行。第一个异常没有被默默吞下,它被捕获到了 catch 块中。
-
@Lucass 肯定被吞了。我刚刚为您添加了一个 Java 示例 ;-)
标签: java c++ exception-handling