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.

Share the Post:
Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular

XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several