Replace the OnError statement with structured exception handling.
Remarks
Prior versions of Visual Basic employed unstructured error handling through the OnError statement. Placing this statement at the beginning of a code block handled any errors that occurred within the block:
Sub DeleteFile()
On Error GoTo PROC_ERR
System.IO.File.Delete "C:\TempFile.txt"
PROC_ERR: MsgBox(Err.Number & ": " & Err.Description)
End Sub
Although Visual Basic .NET supports the OnError statement, you should avoid using this legacy error handling and take advantage of Visual Basic .NET's structured exception handling. Structured Exception Handling has many advantages, including:
- While the OnError statement is not portable to other languages, structured exception handling is supported in other .NET languages.
- Structured Exception Handling exposes full exception information identifying the exception and the location in code where it occurred.
- Structured Exception Handling offers the ability to centralize exception handling at an application's top level.
Resolution
Replace the legacy VB error handling code with a Try statement, made up of the following blocks:
Try block containing the statement to be executed.
Catch block containing the statement which handles the exception.
Finally block containing actions to take when the Try statement is exited (regardless of whether an exception occurred).
For instance, you could modify the example above to use structured exception handling:
Module NewClass
Sub DoSomething()
Try
System.IO.File.Delete("C:\TempFile.txt")
Catch notFound As System.IO.FileNotFoundException
' Do nothing, since the file doesn't exist.
Catch e As Exception
MsgBox(e.Message)
Finally
Console.WriteLine("Process complete.")
End Try
End Sub
See Also
Exception Handling Changes in Visual Basic
Try...Catch...Finally Statements
Handling Exceptions