Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
(ebook) Visual Studio .NET Mastering Visual Basic.pdf
Скачиваний:
120
Добавлен:
17.08.2013
Размер:
15.38 Mб
Скачать

800 Chapter 17 ERROR HANDLING AND DEBUGGING

The final MsgBox is not valid because the oEX variable that it attempts to display is not in scope at this point of the procedure. The two oEX variables have scope only in their Catch blocks.

Finally (!)

You’ll recall that when an exception is generated and handled by a Catch statement, the code execution is immediately transferred to the first relevant Catch exception handler block and then continues on out of the Try…Catch…End Try block. Sometimes, it might be necessary to perform some cleanup before moving out of the exception-handling block. Consider the procedure demonstrated in Listing 17.6.

Listing 17.6: A Possible Exception

Protected Sub ReadFromATextFile(cFilename as string) Dim s As StreamReader

Dim cLine As String

Dim bDone As Boolean = False lbresults.Items.Clear()

s = New Streamreader(cFilename) Try

While Not bDone

cLine = s.ReadLine()

If cLine Is Nothing Then bDone = True

Else

Call lbresults.Items.Add(cLine) End If

End While s.Close()

Catch oEX as Exception

Call MsgBox(“some error occurred”) End Try

End Sub

This method attempts to read the contents of a text file and put the results into a ListBox,

line by line. Most of the reading code is wrapped within a generic exception handler. If an exception is encountered in the main loop, then the s.Close() line will in all likelihood not be executed. This means that our file stream will never be properly closed, possibly leading to a resource leak.

Fortunately, there is an additional type of block available in exception handlers that specifically allow us to avoid this type of problem. This new block is called the Finally block. The code within a Finally block always executes, whether an exception is generated or not. The code in Listing 17.7 is the same as the method in Listing 17.6 but now modified to wrap the s.Close() method inside a Finally block.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

EXCEPTIONS AND STRUCTURED EXCEPTION HANDLING 801

Listing 17.7: Handling an Exception with a Finally Block

Protected Sub ReadFromATextFile(cFilename as string) Dim s As StreamReader

Dim cLine As String

Dim bDone As Boolean = False lbresults.Items.Clear()

s = New Streamreader(cFilename) Try

While Not bDone

cLine = s.ReadLine()

If cLine Is Nothing Then bDone = True

Else

Call lbresults.Items.Add(cLine) End If

End While

Catch oEX as Exception

Call MsgBox(“some error occurred”) Finally

s.Close() End Try

End Sub

Here, you see that any exception within the file-reading loop will be handled with a message box, and then the StreamReader object is closed inside the Finally block. This close statement runs whether the code within the Try…Catch block succeeds or fails. This allows you to guarantee that certain resources or handlers are properly disposed of when they are no longer needed.

Customizing Exception Handling

There are hundreds of exception classes built into the .NET Framework, and you may not want to handle all of them the same way. You can customize the way certain exceptions are handled by bringing up the Exceptions dialog (Figure 17.8) found in the Debug menu.

The exception shown in the Figure is one we saw in the earlier examples, System.NullReferenceException. When this exception is first encountered, the system is currently set to do whatever

the parent setting specifies. Tracing up the tree in this dialog, we eventually find that all .NET Framework exceptions are set to continue when they are first encountered, but to break into the debugger if they are not handled in a Try…Catch…Finally…End Try block. This is consistent with what we saw in the earliest exception examples—a dialog would be displayed when an

exception was encountered, but that dialog would disappear once we wrote the proper exceptionhandling code.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

802 Chapter 17 ERROR HANDLING AND DEBUGGING

Figure 17.8

The Debug

Exceptions dialog

Throwing Your Own Exceptions

As you become more adept at writing VB.NET classes, you will probably encounter the need to throw your own exceptions. Imagine writing the code for an integer property that has a certain range. If a fellow developer is using your class and attempts to set the property to a value beyond this range, you would probably want to inform the developer that he has entered an invalid value. The best way to inform him of this problem is to send him an exception. That way, the developer using your class can choose to handle this error in his own way by writing an exception handler in his code. Listing 17.8 is an example of “throwing” an exception.

Listing 17.8: Throwing an Exception

Private FValue As Integer = 0

Property Value() As Integer

Get

Return FValue

End Get

Set(ByVal iValue As Integer)

If iValue <= FMax Then

FValue = iValue

Else

FValue = FMax

Throw New OverflowException(_

“Cannot set ProgressBar value to greater than maximum.”)

End If

Invalidate()

End Set

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com