Global Exception Handlers

Exceptions bubble up to the parent method. For example, in the following console application, Sub Main has an exception handler and calls the function DivideByZero. When DivideByZero causes an exception, because the function itself has no exception handler, the exception bubbles up to the method that called it—the parent method Sub Main.

Sub Main()
  Try
    'Try dividing 1 by 0
    DivideByZero(1)
  Catch ex As Exception
    MsgBox(ex.ToString)
  End Try
End Sub
Function DivideByZero(ByVal MyNumber As Integer) _
  As Integer
  'Return the input divided by zero
  'This will always cause an exception
  Return MyNumber / 0
End Function

Putting an exception handler in Sub Main gives the effect of a global exception handler. If an uncaught exception ...

Get Security for Microsoft® Visual Basic® .NET now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.