假设你有以下代码:
而不是做:
- Try
- '
- ' Initialize some objects
- '
- '
- ' do something that fails
- '
- '
- ' Clean up-code that gets not reached because exception
- '
- Catch e As Exception
- '
- 'Clean up initialized objects
- '
- Throw e
- End Try
我想做:
- Try
- '
- ' Initialize some objects
- '
- '
- ' do something that fails
- '
- Catch e As Exception
- Throw e
- Finally
- '
- 'Clean up initialized objects
- '
- End Try
所以我的简单的问题是:如果一个例外是finally块到达,即使有一个线之前呢?
[编辑]
感谢您的快速答复。
在第一行,我会考虑NullReference-,COM-和FileNotFound-Exceptions。
好的,我会去这个代码:
- Try
- '
- ' Initialize some objects
- '
- '
- ' do something that fails
- '
- Catch e As Exception ' or just "Catch"??
- Throw
- Finally
- '
- 'Clean up initialized objects
- '
- End Try
祝一切顺利!
英诺
So my simple question is: In case of an exception is the finally block reached even if there is a throw some lines before?
是。 Finally
block始终处于执行状态,准确地进行清理。在你的代码中,删除Catch块,它什么都不做。更糟糕的是,它实际上破坏了堆栈跟踪,因为你不会重新抛出原始的异常,你会抛出一个新的异常。
如果您真的需要一个Catch块,然后重新抛出异常,请使用以下命令:
- Catch e As XyzException
- ' … do some stuff. '
- Throw
- End Try
1):注意事项:有一些例外,如StackOverflowException(如何适合…)需要特别注意,可能不会触发Finally块。正确处理它们通常是相当困难的。