vb.neterror-handlingtry-catchvb6-migration

vb.net - error handling on main method or every method


I have a program that is interacting with emails. I am upgrading it from vb6 to vb.net. There was extensive error handling in the program before ,using On Error commands, to ensure that it never broke, just ignored and logged the errors. In most functions there is this On Error code, where it handles an error in the function by returning a default value and exiting the function. For Example:

Public Function Init() As Boolean
    On Error GoTo Err_Init
    Init = True
Exit_Init: 
    Exit Function 
Err_Init:
    Init = False
    Resume Exit_Init
End Function

I want to change all error handling to Try - Catch blocks. My initial thought when I was upgrading the vb6 code was to replace all error handling with a simple Try - Catch around the Sub Main entry point, as below:

Public Sub Main()
    Try
        Init()
    catch
        'do stuff
    end try
End Sub

public function Init() As boolean
    init = true
end function 

as any errors in the program would be caught in this way and I could handle them all in one Try - Catch.

However I then realised that, that would not make the function above return a value of False when an error occurred. If I still want this functionality do I have to wrap everything in Try blocks?


Solution

  • Since your concern is that you do not want the application to crash or break, Yes you can use Try cache block for that concern. However, If you are talking about error handling in the whole application, then I would suggest that you think of a way to refactor the whole code. Remove all the "On Error" statements and apply some new logic to handle the errors. That logic could vary (Only logging, Retrying strategy Design pattern, etc) Think of all the expected errors and handle them accordingly.