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:
Share on facebook
Share on twitter
Share on linkedin


The Latest

homes in the real estate industry

Exploring the Latest Tech Trends Impacting the Real Estate Industry

The real estate industry is changing thanks to the newest technological advancements. These new developments — from blockchain and AI to virtual reality and 3D printing — are poised to change how we buy and sell homes. Real estate brokers, buyers, sellers, wholesale real estate professionals, fix and flippers, and beyond may

man on floor with data

DevX Quick Guide to Data Ingestion

One of the biggest trends of the 21st century is the massive surge in internet usage. With major innovations such as smart technology, social media, and online shopping sites, the internet has become an essential part of everyday life for a large portion of the population. Due to this internet

payment via phone

7 Ways Technology Has Changed Traditional Payments

In today’s digital world, technology has changed how we make payments. From contactless cards to mobile wallets, it’s now easier to pay for goods and services without carrying cash or using a checkbook. This article will look at seven of the most significant ways technology has transformed traditional payment methods.