How do you throw an exception?

Q: How do you throw an exception?

A: The Throw() method is used to induce an error into the error handling routine. To generate an error, simply declare an object of type "Exception" with the desired message. Then call the Throw() method to send this error message to the error handling routine ("Catch" block). Once Throw() is called, all intermediate code will be skipped and execution will transfer to the "Catch" block, where Ex.Message="Something wrong happened!" See the code example listed below:

Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
Try

'Some code logic here...

Dim ex As New Exception("Something wrong happened!")
Throw ex

'Some code logic here...

Catch ex As Exception 'Catch a generic exception.
Dim strMsg As String
strMsg = "Error: " & Ex.Message & ControlChars.CrLf
strMsg &= "Stack Trace: " & Ex.StackTrace & ControlChars.CrLf

lblError.Text = strMsg
End Try

End Sub

Comments

Popular posts from this blog

Working with double quotes (") in VB.Net

Using VB Script to display part of an IP address

Sep '19 Announcements