Exceptions/Catch an exception thrown in a nested call: Difference between revisions

Line 3,033:
baz threw a user-defined empty string exception
U1</pre>
 
=={{header|Visual Basic .NET}}==
 
<lang vbnet>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</lang>
 
Control passes to the Catch block after U0 is thrown, and so the second call to Bar() is not made.
 
{{out}}
<pre>U0 caught.</pre>
 
To prevent this, a loop can be used to run the entire Try statement twice:
 
<lang vbnet> Sub Foo()
For i = 1 To 2
Try
Bar()
Catch ex As U0
Console.WriteLine(ex.GetType().Name & " caught.")
End Try
Next
End Sub</lang>
 
{{out}}
<pre>U0 caught.
 
Unhandled Exception: U1: Exception of type 'U1' was thrown.
at Program.Baz() in Program.vb:line 34
at Program.Bar() in Program.vb:line 25
at Program.Foo() in Program.vb:line 17
at Program.Main() in Program.vb:line 11</pre>
 
=={{header|zkl}}==
Anonymous user