Close()
End If
End Try
End Sub
Public Shared Sub DoSomeMoreStuff()
'Open a file
Dim fs As FileStream = Nothing
Try
fs = File.Open("log.txt", FileMode.Append, FileAccess.Write, _
FileShare.None)
Dim msg As Byte() = New UTF8Encoding(True).GetBytes("Doing Some" & _
"More Stuff")
fs.Write(msg, 0, msg.Length)
Finally
If Not (fs Is Nothing) Then
fs.Close()
End If
End Try
End Sub
Shared Sub Main()
DoSomeStuff()
DoSomeMoreStuff()
End Sub
End Class
The Try/Finally blocks solve the problem, but that was a lot of extra typing. Moreover, it
makes the code difficult to read. As you??™d expect, there is a better way. Many objects, such as
FileStream, that have a Close method also implement the IDisposable pattern. Usually, calling
Dispose() on these objects is the same as calling Close(). Of course, calling Close() over
Dispose() or vice versa is arguing over apples and oranges, if you still have to explicitly call
one or the other. Thankfully, there??™s a good reason why most classes that have a Close method
implement Dispose()??”so you can use them effectively with the Using keyword, which is typically
used as part of the Disposable pattern. Therefore, you could change the code to the
following:
CHAPTER 8 n EXCEPTION HANDLING 160
Imports System
Imports System.
Pages:
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274