devxlogo

Add exception tracing with one line of code

Add exception tracing with one line of code

At times you want to keep a log of all the exception occurred in your application, including those that are correctly caught by a Catch block. At first you might believe that you need to add a call to the LogException procedure from each and every Catch block, which is clearly a nuisance:

Try    ' do something    ' ...Catch ex As FileNotFoundException    Debug.WriteLine(ex.Message)    ' ...Catch ex As DivisionByZeroException    Debug.WriteLine(ex.Message)    ' ...Catch ex As Exception    Debug.WriteLine(ex.Message)    ' ...End Try

Visual Basic .NET supports the When clause in exception filters, which makes this task much simpler. As a matter of fact, you just need one single statement for each Try block that you want to keep under observation:

Try    ' do something    ' ...Catch ex As Exception When LogException(ex)Catch ex As FileNotFoundException    ' ...Catch ex As DivisionByZeroException    ' ...Catch ex As Exception    ' ...End Try

The LogException is a function defined in a Module block, that does the actual logging and always returns False:

Function LogException(ByVal ex As Exception) As Boolean    Debug.WriteLine(ex.Message)    Return FalseEnd Function

Here’s how it works. The Catch clause soon after the Try block traps a generic Exception object, and therefore matches all exceptions, so Visual Basic evaluates the When clause to see whether its expression returns True. At this point the LogException function is invoked, so you have an opportunity to log the exception somewhere. Just remember that you must return False so that VB.NET then ignores this Catch and passes to the ones that follow it, where the exception is actually processed.

See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist