6.4. Resuming Code

Sometimes you'll just want to keep on trucking after an error has occurred rather than handle it. Example 6-7 demonstrates an unstructured approach to ignoring errors. Normally this code would throw a DivideByZeroException, but here On Error Resume Next is used to prevent exceptions from propagating out of the method.

Example 6-7. On Error Resume Next
'Throws System.DivideByZeroException  
Public Class App
  Public Shared Sub Main( )
    On Error Resume Next
    Dim x As Integer = 0
    Dim y As Integer = 10 \ x
    'Use x and y here
  End Sub
End Class

Many of you know that ignoring errors like this is considered bad practice. Even so (or so you say), sometimes it needs to be done. A safer approach would be to turn off error handling specifically where you need to, and then turn it back on when you are done:

Public Sub SomeMethod( )
    On Error Goto errHandler
   
    On Error Resume Next
    'Code that might trigger errors goes here
				On Error Goto errHandler
   
    Exit Sub
errHandler:
    'Handle errors here    
End Sub

There are several arguments against this approach. Handling (or not handling) errors in this way does not produce the most readable code. Program flow jumps all over the place. Also, if this technique is used in a method that contains even a small degree of complexity, debugging could turn into a nightmare.

On Error Resume Next results in inefficient code. It might be one line of code in VB, but you'd be amazed by the IL spaghetti that is generated by the compiler. Remember Example 6-7 ...

Get Object-Oriented Programming with Visual Basic .NET now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.