【发布时间】:2010-04-09 20:55:32
【问题描述】:
我该怎么做?
void x()
{....
if (...)
{try
{}
catch (ComException com)
{ throw com}
finally // in any case, executed fine!
{...instructions.......}
}
... instructions...// not executed in case of exception because the finally can't embrace the following code too... but this block of code needs to be executed in any case too...
{}
}
【问题讨论】:
-
为什么要在 catch 块中抛出异常?
-
@Matthew Jones 我猜 OP 在 catch 块中省略了一些日志记录代码。否则是的,捕捉和重新抛出是没有意义的。
-
因为我必须捕获一个特殊的异常,即 Com 异常,然后将其扔给调用方法,也许语法可以减轻......(我在 c# 中)......但没有catch 中除了 throw 没有其他代码。否则你会怎么写?
-
@Anna:捕获异常而不是再次抛出异常有什么意义?仍然可能引发其他异常,因为您没有捕获它们(您必须添加
catch (Exception ex)作为最后一个catch才能这样做)。当重新抛出异常时使用throw;,而不是throw ex;。这使调用堆栈和行号保持不变。 -
关键是我需要抛出这个异常,但我需要 finally 才能继续代码。那么我应该如何在语法上使用 finally 而不使用 catch 呢?
标签: c# if-statement try-catch try-catch-finally