Helixoft Blog

Peter Macej - lead developer of VSdocman - talks about Visual Studio tips and automation

Converting "On Error..." To "Try...Catch"

We all know that we should use Try ... Catch instead of On Error... But our VSdocman contains some code ported from VB6. This code naturally uses On Error... and it was OK as long as the code worked correctly.

Recently, we decided to clean the old code and use String.equals method for comparing two strings instead of = operator. And suddenly On Error Resume Next wasn't good anymore. If the original method was

Function test(ByVal str As String) As Integer
    On Error Resume Next
    If str = "a" Then
        Return 1
    End If
    Return 0
End Function

and you called it with Nothing argument, it worked as expected and returned 0. But if you called modified version

Function test(ByVal str As String) As Integer
    On Error Resume Next
    If str.equals("a") Then
        Return 1
    End If
    Return 0
End Function

with Nothing argument, it returned 1. str.equals failed because str was Nothing. On Error Resume Next didn't skip whole If...Then block but continued on the very next line.

So there was good reason to remove all old On Error Resume Next statements. It's not possible to automatically remove On Error Resume Next lines and place Try...Catch block on whole function. What if I don't want to exit the function on the first exception but I want to catch it and continue? I need to decide myself where to insert Try...Catch blocks. I've used MZ-Tools add-in for that. I deleted On Error Resume Next lines manually and then used MZ-Tools' Add Exception Handler function which surrounds selected text with your predefined pattern. In my case it was

Try
    ...
Catch ex As Exception
End Try

 

Comments are now closed for this entry

 

Start generating your .NET documentation now!
DOWNLOAD
Free, fully functional trial