Try
Finally
End Try
How can this be used if there's no Catch block?
Printable View
Try
Finally
End Try
How can this be used if there's no Catch block?
It is permissible to leave out the Catch, although its hard to see a good reason. This would allow some extra code to be run after an exception has occurred, that exception could then be caught by the ApplicationEvents UnhandledException handler.
I can't think of a good reason to do that other than perhaps passing a message to provide some information about in which sub/function the exception occurred.
In the global exception handler, it could then be;Code:Public OriginofException As String = String.Empty
Private Sub Nonsense()
Try
Dim s As New IO.StreamReader("DoesNotExist.txt")
Finally
OriginofException = "Nonsense"
End Try
End Sub
Code:Namespace My
Partial Friend Class MyApplication
Private Sub MyApplication_UnhandledException( _
ByVal sender As Object, _
ByVal e As Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs) _
Handles Me.UnhandledException
MessageBox.Show("Exception came from: " & Form1.OriginofException.ToString)
End Sub
End Class
End Namespace
Interesting,
Private Sub Nonsense() seems to be the answer.
Thanks
Q. What's a Try block for?
A. To attempt to execute code that may throw an exception.
Q. What's a Catch block for?
A. To catch an exception and deal with it.
Q. What's a Finally block for?
A. To perform cleanup that must be done whether an exception is thrown or not.
Q. What if you need to perform cleanup but you don't want to catch any exceptions?
A. You have a Try block with a Finally block but no Catch block. That way the required cleanup is performed but amy exceptions will bubble up to the caller to be caught there, which is a completely legitimate design.
So we would be trying to catch the error at a higher level on purpose. And MS has given us the flexibility to do that.
I understand.
Thanks