I am in the process of updating some vb6
code to vb.net
. The error handling in this old code uses On Error GoTo
or On Error Resume Next
with error handles at the end of each method.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
Now that I am updating this code to vb.net
I am changing all error handling to try - catch
statements. I can either wrap the Public Sub Main
function in a try - catch
statement and catch all errors at the top level or swap out the above code for the following:
Public Function Init() As Boolean
Try
Init = True
catch e As exception
Init = false
End Try
End Function
My Problem comes when, in the old code, a custom error is set (Error 9999
) if certain If
statements are not met. In the Error handles at the end of the function, it checks if the error is not 9999
. If it is not then it handles it appropriately. Using the first example:
Public Function Init() As Boolean
On Error GoTo Err_Init
Dim a As Integer
If (a <> 10)
Init = True
Else
Error 9999
End If
Exit_Init:
Exit Function
Err_Init:
If (Err.number() <> 9999)
Init = False
End If
Resume Exit_Init
End Function
So my question is, how can I use try-catch
statements to replicate this error 9999
, as throughout my code it will not always be the same exception that is thrown, hence why just throwing a custom error 9999
could be used across the board and used to mark the errors that could be ignored, and then you can just catch the important errors. Is there a way to Throw New Exception(Id = 9999)
, sort of thing?
You should create a custom exception and treat separetly in your catch. Here's some example on how to create your custom exception: https://msdn.microsoft.com/en-us/library/87cdya3t(v=vs.110).aspx
And then code something this way:
Public Function Init() As Boolean
Try
If (a = 10) Then
Throw New YourCustomException()
End If
Catch yourEx As YourCustomException
'Do whatever you want to do when the code throws your custom exception
Catch generalException As Exception
Return False
End Try
Return True
End Function