[Visual Basic] How To Perform Basic Error Handling And Show The Error In Message Box?

No program is perfect and some error can happen at some stage. If you’re a developer, you already know the way .NET Framework shows an error to user which looks like the below image. It is a highly unfriendly dialog box and most users can’t even get to know what has happened with the program. Today, I will be showing you how to show an error in a friendly manner to the user.

Let us consider you are using the following code for your program:

My.Computer.Registry.LocalMachine.OpenSubKey(“Example”, True).CreateSubKey(“SIDHU”)

In this code, the program will open the Registry Editor then will go to the LOCAL_MACHINE and will then try to open Examplesubkey. But there’s no such subkey available. Hence the program will populate the unfriendly box containing the error. To fix this, we modify the code like below:


My.Computer.Registry.LocalMachine.OpenSubKey(“Example”, True).CreateSubKey(“SIDHU”)

Catchex AsException

MsgBox(ex.Message & Environment.NewLine & Environment.NewLine & ex.StackTrace, MsgBoxStyle.Critical)


So what we did? The code between Try and Catch statement will be executed once operation starts. If any error occurs, the code between Catch and End Try statement will be executed. This code will present a Message Box containing the main error text followed by more details about error understandable by developer just like the image below:

ex refers to the exception as we declared in the line “Catch ex as Exception”. Environment.NewLine code will leave the current line and starts from another. ex.StackTrace will give some more details about the error as shown in the image above.

Join Us On Facebook and Twitter and you can subscribe via email too

Related posts