pocpoc47
pocpoc47

Reputation: 95

Exit parent Sub

I am a bit confused how to handle the errors in a VB .net app I am writing.

This is what I have:

Private Sub Func1()
 Try
   'stuff that could raise an error

 Catch ex As Exception
   MsgBox("There is an error" & ex)
   End
 End Try

End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
  Func1()
 'a lot of stuff that will also raise an error is Func1 does
End Sub

This code will exit the application if there is an error.

If I remove the "End", it will go on and raise multiple errors in the Sub Button1_click.

So I need to put something in the Func1 that could interrupt execution the Sub Button1_click.

I could put Exit Sub but I have a lot of Subs that use this Func1 so I'd prefer a way to do it from Func1.

Upvotes: 1

Views: 2348

Answers (2)

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239654

Don't catch the exception at such a low level if all you want to do is show the text to the user.

Install a handler in the Application.ThreadException and/or AppDomain.UnhandledException events and do your MsgBox call there.

If you do that, there's no need for the Try/Catch block at all in Func1 and, if an exception occurs, the remainder of Func1 and Button1_Click don't run.

Upvotes: 0

Steve
Steve

Reputation: 216293

If you don't want to continue exection of Button1_Click if Func1 fails then change Func1 to a boolean Function

Private Function Func1() As Boolean
 Try
   'stuff that could raise an error

   Return True
 Catch ex As Exception
   MsgBox("There is an error" & ex)
   return False
 End Try

End Function

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
  if Func1() = True Then
     'a lot of stuff that will also raise an error is Func1 does
  End If
End Sub

Upvotes: 1

Related Questions