Because VB 2005 still supports the older On Error statement, it is possible that you will use code that handles errors that way instead of with structured exception handling. You can use both techniques in a single program, but it is not possible to use both forms in a single routine. If you attempt to use both On Error and Try...Catch in a single routine, you will get a syntax error.
The VB compiler does allow the two techniques for handling errors to communicate with each other. For example, suppose you have a routine that uses On Error and then uses Err.Raise to promote the error to the calling code. Also suppose that the calling code makes the call in a Try...Catch block. In that case, the error created by Err.Raise becomes an exception in the calling code and is trapped by a Catch block just as a normal exception would be. Here’s a code example to illustrate.
First, create a subroutine that creates an error with Err.Raise, like this:
Private Sub RaiseErrorWithErrRaise() Err.Raise(53) ' indicates File Not Found End Sub
Then call this routine from a button’s click event, with the call inside a Try...Catch block:
Private Sub Button2_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button2.Click Try RaiseErrorWithErrRaise() Catch ex As Exception MessageBox.Show(ex.Message) End Try End Sub
When the button is clicked, it will display a message box with File Not Found. Even though the File Not Found error is raised by Err.Raise, it is translated to a .NET exception automatically.
Similarly, exceptions that are generated by a Throw statement in a called routine can be trapped by On Error in a calling routine. The exception is then translated into an Err object that works like the VB6 Err object.