Propagation of Exceptions in VB.NET

In this article I will explain you about Propagation of Exceptions in VB.NET.
  • 1948
 

Whenever an exception occurs in a try block, the corresponding catch blocks are checked to see if they can catch the exception. If no matching exception is found even if a finally block is executed the exception is propagated to a higher-level try block. This process repeats until the exception is caught but if it is not caught, the program execution comes to an end. In other words, if the top of the call stack is reached without finding a catch block handling the exception, the default exception handler handles it and then the application terminates. If an exception is thrown from inside a catch clause when any finally block is present the finally block is executed, and the exception is propagated to higher-level exceptions. Similarly, if an exception is thrown from within a finally block, this exception is propagated to a higher-level try clause.

The example given below demonstrates propagation of exceptions.

Example of Exception

    Imports System.Text

    Public Class TestPropagation
        Public Shared Sub Main()
            Try
                '3
                Try
                    '2
                    Try
                        '1
                        Throw New ArgumentException()
                    Catch e As NullReferenceException
                        '1
                        Console.WriteLine("Inside catch 1")
                    Finally
                        '1
                        Console.WriteLine("Inside finally 1")
                        '1
                    End Try
                Catch
e As NullReferenceException
                    '2
                    Console.WriteLine("Inside catch 2")
                Finally
                    '2
                    Console.WriteLine("Inside finally 2")
                    '2
                End Try
            Catch
e As Exception
                '3
                'try catching some other Exception instead
                'of general Exception and ArgumentException
                'Program would throw unhandled System.ArgumentException: value
                'does not fall within the expected range
                Console.WriteLine("Inside catch 3")
            Finally
                '3
                Console.WriteLine("Inside finally 3")
            End Try
            '3
            Console.ReadLine()
        End Sub
    End
Class

Output of the above example

Exception.gif
 

Conclusion

Hope this article would have helped you in understanding Propagation of Exceptions in VB.NET.

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.