O'Reilly logo

Programming Visual Basic .NET, Second Edition by Jesse Liberty

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Rethrowing Exceptions

You might want your catch block to take some initial corrective action and then rethrow the exception to an outer try block (in a calling function). It might rethrow the same exception, or it might throw a different one. If it throws a different one, it may want to embed the original exception inside the new one so that the calling method can understand the exception history. The InnerException property of the new exception retrieves the original exception.

Because the InnerException is also an exception, it too might have an inner exception. Thus, an entire chain of exceptions can be nested one within the other, much like Ukrainian dolls are contained one within the other. Example 11-8 illustrates.

Example 11-8. Rethrowing and inner exceptions

Option Strict On Imports System Namespace Programming_VBNET Public Class MyCustomException Inherits System.ApplicationException Public Sub New(ByVal message As String, ByVal inner As Exception) MyBase.New(message, inner) End Sub 'New End Class 'MyCustomException Public Class Test Public Shared Sub Main( ) Dim t As New Test( ) t.TestFunc( ) End Sub 'Main Public Sub TestFunc( ) Try DangerousFunc1( ) ' if you catch a custom exception ' print the exception history Catch e As MyCustomException Console.WriteLine(ControlChars.Lf + "{0}", e.Message) Console.WriteLine("Retrieving exception history...") Dim inner As Exception = e.InnerException While Not (inner Is Nothing) Console.WriteLine("{0}", inner.Message) inner = inner.InnerException ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required