The reason is that the
catch
block gets executed only if an
exception
is thrown, whereas the
finally
block gets executed both in case of normal execution without an exception and in case an exception occurs.
So, in the second example the
port.Close
gets executed only when an exception occurs and remains open in the normal execution. As per MSDN documentation for an object implementing the
IDisposable
interface the
Dispose
method is to be called in the
finally
block.
The disposable pattern is implemented with
IDisposable
interface to ensure that the resources held by an object are released properly.
The
try finally
block is implicitly implemented by the
using block
and it is convenient to use
using
block with an object implementing
IDisposable
interface as explained here
http://msdn.microsoft.com/en-us/library/yh598w02.aspx[
^]