I noticed in System.Threading.TimerBase.Dispose()
the method has a try{} finally{}
block but the try{}
is empty.
Is there any value in using try{} finally{}
with an empty try
?
http://labs.developerfusion.co.uk/SourceViewer/browse.aspx?assembly=SSCLI&namespace=System.Threading&type=TimerBase
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] internal bool Dispose(WaitHandle notifyObject) { bool status = false; bool bLockTaken = false; RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { do { if (Interlocked.CompareExchange(ref m_lock, 1, 0) == 0) { bLockTaken = true; try { status = DeleteTimerNative(notifyObject.SafeWaitHandle); } finally { m_lock = 0; } } Thread.SpinWait(1); // yield to processor } while (!bLockTaken); GC.SuppressFinalize(this); } return status; }
By using a finally block, you can clean up any resources that are allocated in a try block, and you can run code even if an exception occurs in the try block. Typically, the statements of a finally block run when control leaves a try statement.
As such, an empty finally block is most probably the sign of potential "resource leaks" that will jeopardize the application's stability. Add code to the finally block, especially the release of resources used in the try block, if any.
try block will work fine if nothing is in it . You cannot use any checked exception in a catch block if it is never thrown. so with the empty try block u can use catch with unchecked exceptions if exception is thrown or not but u can use checked exception only if it is thrown.
Generally try-finally is used to assure that some piece of code gets executed irrespective if the exception occurs or not. Catch block is generally missing because code in try block does not throw any checked exception which can be caught.
From http://blog.somecreativity.com/2008/04/10/the-empty-try-block-mystery/:
This methodology guards against a Thread.Abort call interrupting the processing. The MSDN page of Thread.Abort says that “Unexecuted finally blocks are executed before the thread is aborted”. So in order to guarantee that your processing finishes even if your thread is aborted in the middle by someone calling Abort on your thread, you can place all your code in the finally block (the alternative is to write code in the “catch” block to determine where you were before “try” was interrupted by Abort and proceed from there if you want to).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With