ProgrammingVB.NET Developer

How to implement custom exception handling in Visual Basic and in what cases is it really necessary?

Pass interviews with Hintsage AI assistant

Answer.

In Visual Basic .NET, you can create your own exception types to explicitly indicate specific errors that occur in the application. To do this, you need to inherit a new class from System.Exception (or one of its descendants) and, if necessary, add new properties to convey additional information.

Custom Exceptions allow you to make the code more readable and maintainable, especially if you need specific handling for certain business scenarios.

Example:

Public Class InvalidUserNameException Inherits ApplicationException Public Sub New(message As String) MyBase.New(message) End Sub End Class ' Usage: Sub ValidateUserName(userName As String) If userName = "" Then Throw New InvalidUserNameException("User name cannot be empty") End If End Sub

Trick question.

Question: "Can you just throw a string using Throw "Error" in Visual Basic, and will it be handled by Try...Catch?"

Answer: No, that is not allowed. The Throw statement requires an object of type Exception. Attempting to throw a string (Throw "err") will lead to a compilation error. You must always create a new instance of the Exception class or its descendant.

Example of incorrect code:

' This will cause an error! Throw "Error!"

Example of correct code:

Throw New Exception("Error!")

Examples of real errors due to lack of knowledge on the topic.


Story:

In a large project, one of the developers was throwing exceptions with Throw "Invalid data!". This led to compilation errors in production, as the code did not pass static checks. The lack of proper exception handling delayed the release by a week — all instances of using throw with strings had to be searched and rewritten throughout the code.


Story:

The team created custom exceptions without adding a constructor with the InnerException parameter. During the diagnosis of complex errors, the call stack was lost due to the inability to "nest" the original exception. As a result, it was difficult to find the root cause of the failure.


Story:

In a media application, a custom exception was used too frequently and inappropriately (for example, with every incorrect input). As a result, system performance dropped — because generating exceptions is operationally costly. After a review, some of these exceptions were replaced with regular condition checks.