如何在finally中抛出异常

时间:2011-06-21 22:17:33

标签: .net

我们假设我们有这样的代码:

int x = 0;

try
{
    try
    {
        x /= x; // DivideByZeroException
    }
    finally
    {
        throw new OverflowException("foobar"); // how to pass thrown exception here
    }
}
catch(Exception e)
{
    System.Console.WriteLine(e.Message);
}

是否有可能在finally中获得抛出异常并将其作为OverflowException的第二个参数传递?

UPD :各位,我确实知道如何使用catch,我知道从最后抛出异常是一种奇怪的做法。< / p>

但最初的问题(肯定有科学性,不实用)我们可以在finally 中检索抛出的异常吗?

是(那怎么样)?没有?这就是我想要看的全部。

3 个答案:

答案 0 :(得分:1)

从终极投掷通常被认为是一个坏主意。这是因为它隐藏了第一个例外。请参阅此stackoverflow post

This might be better:
try
{
    try
    {
        x /= x; // DivideByZeroException
    }
    catch (DivideByZeroException dbze)
    {
        throw new OverflowException("foobar", dbze); // how to pass thrown exception here
    }
}
catch(Exception e)
{
    System.Console.WriteLine(e.Message);
}

答案 1 :(得分:0)

我认为你只想在一个catch中捕获它,然后用你想要的任何值作为参数重新抛出它或另一个异常。你为什么要用finally来做这个?

答案 2 :(得分:0)

实践是首先捕获特定的异常,然后更通用。 finally应该只用于“清理”try块中使用的任何对象。例如,如果您只有OverflowException必须发生的逻辑,请尝试

try
{
  // do stuff
}
catch(OverflowException ex)
{
  // do specific stuff here
}
finally
{
  //clean up here
}

这样做,允许非溢出异常通过,允许其他调用代码处理任何产生的问题。这是首选,因为异常将在所需位置具有完整的跟踪堆栈。在你的问题代码之后,你抛出的Overflowexception的堆栈跟踪只能在你当前的方法中开始,而不是在首先导致异常的代码中。

现在,如果您只想在完成工作后抛出OverFlowException,请使用

throw;

关键字,而不是

throw ex;

命令。 See this blog post for a better description

相关问题