Show how to create a user-defined exception   and   show how to catch an exception raised from several nested calls away.

   Create two user-defined exceptions,   U0   and   U1. 
   Have function   foo   call function   bar   twice.
   Have function   bar   call function   baz. 
   Arrange for function   baz   to raise, or throw exception   U0   on its first call, then exception   U1   on its second.
   Function   foo   should catch only exception   U0,   not   U1.


Show/describe what happens when the program is run.




Class U0
    Inherits Exception
End Class
 
Class U1
    Inherits Exception
End Class
 
Module Program
    Sub Main()
        Foo()
    End Sub
 
    Sub Foo()
        Try
            Bar()
            Bar()
        Catch ex As U0
            Console.WriteLine(ex.GetType.Name & " caught.")
        End Try
    End Sub
 
    Sub Bar()
        Baz()
    End Sub
 
    Sub Baz()
        ' Static local variable is persisted between calls of the method and is initialized only once.
        Static firstCall As Boolean = True
        If firstCall Then
            firstCall = False
            Throw New U0()
        Else
            Throw New U1()
        End If
    End Sub
End Module