I know how to use try-catch-finally. However I do not get the advance of using finally
as I always can place the code after the try-catch block.
Is there any clear example?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
When you have a finally block, the code therein is guaranteed to run upon exit of the try. If you place code outside of the try/catch, that is not the case. A more common example is the one utilized with disposable resources when you use the
using
statement.expands to
This ensures that all unmanaged resources get disposed and released, even in the case of an exception during the
try
.*Note that there are situations when control does not exit the try, and the finally would not actually run. As an easy example,
PowerFailureException
.I am not sure how it is done in c#, but in Delphi, you will find "finally" very often. The keyword is manual memory management.
Update: This is actually not a great answer. On the other hand, maybe it is a good answer because it illustrates a perfect example of
finally
succeeding where a developer (i.e., me) might fail to ensure cleanup properly. In the below code, consider the scenario where an exception other thanSpecificException
is thrown. Then the first example will still perform cleanup, while the second will not, even though the developer may think "I caught the exception and handled it, so surely the subsequent code will run."Everybody's giving reasons to use
try
/finally
without acatch
. It can still make sense to do so with acatch
, even if you're throwing an exception. Consider the case* where you want to return a value.The alternative to the above without a
finally
is (in my opinion) somewhat less readable:*I do think a better example of
try
/catch
/finally
is when the exception is re-thrown (usingthrow
, notthrow ex
—but that's another topic) in thecatch
block, and so thefinally
is necessary as without it code after thetry
/catch
would not run. This is typically accomplished with ausing
statement on anIDisposable
resource, but that's not always the case. Sometimes the cleanup is not specifically aDispose
call (or is more than just aDispose
call).you don't necessarily use it with exceptions. You may have
try/finally
to execute some clean up before everyreturn
in the block.The finally block always is executed irrespective of error obtained or not. It is generally used for cleaning up purposes.
For your question, the general use of Catch is to throw the error back to caller, in such cases the code is finally still executes.
The finally block will always be executed even if the exception is re-thrown in the catch block.