The Exit Try Statement

The Exit Try statement will, under a given circumstance, break out of the Try or Catch block and continue at the Finally block. In the following example, you exit a Catch block if the value of iItems is 0, because you know that your error was caused by that problem:

Private Function GetAverage5(iItems As Integer, iTotal as Integer) As Single

' Code that might throw an exception is wrapped in a Try block. Try

Dim sngAverage As Single

' This will cause an exception to be thrown. sngAverage = CSng(iTotal \ iItems)

' This only executes if the line above generated no error. MessageBox.Show("Calculation successful") Return sngAverage Catch excDivideByZero As DivideByZeroException

' You'll get here with an DivideByZeroException in the Try block. If iItems = 0 Then Return 0 Exit Try


MessageBox.Show("Error not caused by iItems") End If

Throw excDivideByZero

MessageBox.Show("More logic after the thrown - never executed") Catch excGeneric As Exception

' You'll get here when any exception is thrown and not caught in ' a previous Catch block.

MessageBox.Show("Calculation failed - generic exception caught") Throw excGeneric Finally

' Code in the Finally block will always run, even if ' an exception was thrown in a Catch block.

MessageBox.Show("You always get here, with or without an error") End Try End Sub

Code snippet from ExceptionHandlingSampleCodeForm

In your first Catch block, you have inserted an If block so that you can exit the block given a certain condition (in this case, if the overflow exception was caused because the value of iItems was 0). The Exit Try goes immediately to the Finally block and completes the processing there:

If iItems = 0 Then Return 0 Exit Try Else

MessageBox.Show("Error not caused by iItems") End If

Code snippet from ExceptionHandlingSampleCodeForm

Now, if the overflow exception is caused by something other than division by zero, you'll get a message box displaying "Error not caused by iItems."

0 0

Post a comment