Helpful Guide to Exception Handling in VB.Net

Exception handling is an important part of any programming language. It allows you to anticipate and handle errors that might occur in your code. VB.Net is no different, and in this article we’ll show you how to use try…catch blocks to handle exceptions in your VB.Net code.

When an exception occurs, your code can take one of two paths:

It can ignore the exception and hope that it goes away. This is generally not a good idea, as ignoring exceptions can lead to unpredictable results.

It can handle the exception gracefully, allowing your code to continue running even in the face of an error.

Let us now understand what exceptional handling is.

What is exception handling?

Exception handling is a process of dealing with errors that occur during the execution of a program. It is mainly used to prevent the program from crashing and to ensure that the program runs smoothly. Exception handling can be done in various ways, but the most common way is to use try-catch blocks and global exception handling.

Try-catch blocks are used to enclose code that might throw an exception. If an exception is thrown, the code in the catch block is executed. This allows the program to recover from errors and continue running.

Why is exception handling important?

Exception handling is important because it allows you to anticipate and respond to potential errors in your code. By using try/catch blocks, you can gracefully handle exceptions and avoid crashing your program. Additionally, exception handling can help you provide more informative error messages to your users, which can help them debug their own code.

 Moving ahead lets now understand how to handle exceptions in VB.Net.

How to handle exceptions in VB.Net

When it comes to exception handling, VB.Net has a lot to offer. In this blog post, we’ll take a look at how to handle exceptions in VB.Net.

We’ll start by looking at the basics of exception handling. We’ll then move on to some more advanced topics, such as using custom exceptions and creating your own exception classes.

So, let’s get started!

The Basics of Exception Handling

When an error occurs in your code, an exception is thrown. An exception is a special type of error that indicates that something went wrong in your code.

Exception handling is the process of dealing with these errors in your code. Exception handling in VB.NET is built on four keywords i.e. Try, Catch, Finally and Throw. Lets have a look at each of them one by one:

  1. Try: A Try block indicates a section of code for which specific exceptions will be raised. It is followed by one or more Catch blocks.
  • Catch: A programme catches an exception with an exception handler at the point in the programme where the problem should be handled. The Catch keyword denotes capturing an exception.
  • Finally: The Finally block is used to execute a specified set of statements regardless of whether an exception is thrown or not. For example, if you open a file, it must be closed regardless of whether an exception is triggered.
  • Throw: When an issue occurs, a program throws an exception. This is done using a throw keyword.

Let us now understand it with an example:

With an assumption of block raising an exception, using a combination of Try and Catch keywords, a method catches an exception. So we put Try-Catch block around this code. This code is now called as a protected code. Here is the syntax:

Try

   [ tryStatements ]

   [ Exit Try ]

[ Catch [ exception [ As type ] ] [ When expression ]

   [ catchStatements ]

   [ Exit Try ] ]

[ Catch ... ]

[ Finally

   [ finallyStatements ] ]

End Try

If your block raises multiple exceptions, then you can list down multiple catch statements to catch different exceptions.

Let’s introduce you to System.ApplicationException

Exception Classes in .Net Framework

Expect you to be aware of classes in the .net Framework, even exceptions are the representation of types. They are derived from System.Exception class. For example, System.ApplicationException and System.SystemException classes.

The System.ApplicationException class supports exceptions generated by application programs. All the exceptions defined by the programmers should be derived from this class.

The System.SystemException class is the base class for all predefined system exceptions.

Exception Handling: An Example

VB.NET provides a very structured solution for exception handling. That is Try and Catch blocks. Here we use Try, Catch, and Finally keywords. Let us explain it with the help of an example. In this example, it is throwing an exception when divided by zero:

Module exceptionProg

   Sub Division(ByVal num1 As Integer, ByVal num2 As Integer)

      Dim result As Integer

      Try

         result = num1 \ num2

      Catch e As DivideByZeroException

         Console.WriteLine("Exception caught: {0}", e)

      Finally

         Console.WriteLine("Result: {0}", result)

      End Try

   End Sub

   Sub Main()

      Division(25, 0)

      Console.ReadKey()

   End Sub

End Module

Upon execution of the above code following is the result:

Exception caught: System.DivideByZeroException: Attempted to divide by zero. 

at …

Result: 0

In this example, the try block contains the code that might throw an exception, and the catch block contains the code that will execute if an exception gets thrown. The variable represents the exception thrown, and you can use it to access information about the error. It will produce the following output:

“A custom exception is being thrown here.”

“Now inside the Finally Block”

Logging Exceptions: An Example

Below is an example of logging exceptions within VB.NET using the easy to use and integrate ClearInsights SDK.

Imports ClearInsights.Logging
Imports Microsoft.Extensions.DependencyInjection
Imports Microsoft.Extensions.Logging

Module Program
    Sub Main(args As String())

        Dim serviceCollection As New ServiceCollection()
        ConfigureServices(serviceCollection)

        Dim serviceProvider = serviceCollection.BuildServiceProvider()

        'This will automatically catch any unhandled exceptions
        System.AppDomain.CurrentDomain.UseClearInsightsExceptionHandling(serviceProvider.GetService(Of ILogger(Of AppDomain)))

        Dim someClass = serviceProvider.GetService(Of SomeClass)()
        someClass.ExecuteHandledException()
        someClass.ExecuteUnHandledException()
    End Sub

    Private Sub ConfigureServices(ByVal services As IServiceCollection)
        services.AddLogging(Function(configure)
                                Return configure.AddClearInsightsLogger(Sub(configuration)
                                                             configuration.ApiKey = "{ApiKey}"
                                                             configuration.Secret = "{Environment Client Secret}"
                                                             configuration.ApplicationName = "{Your Application Name}"
                                                         End Sub)
                            End Function).AddTransient(Of SomeClass)()

    End Sub
End Module


Public Class SomeClass
    Private ReadOnly _logger As ILogger(Of SomeClass)

    Public Sub New(logger As ILogger(Of SomeClass))
        _logger = logger
    End Sub

    Public Sub ExecuteHandledException()
        Try
            Throw New ArgumentNullException()
        Catch ex As Exception
            _logger.LogError(ex, ex.Message)
        End Try
    End Sub

    Public Sub ExecuteUnHandledException()
        Throw New ArgumentNullException()
    End Sub
End Class

ClearInsights is a centralized application logging platform that integrates with your team’s project management platform to automatically add new errors to your backlog. For more information on ClearInsights, check out ClearInsights Logging.

Conclusion

Exception handling is an essential component of every programming language, including VB.Net. Understanding how to handle exceptions properly ensures that your code runs smoothly and efficiently without any unexpected errors or bugs. We hope you could learn from this article and understand the basics of exception handling in VB.Net, and that you can use this knowledge to write better code in the future.

ClearInsights Centralized Application
Logging & Monitoring

Fully integrated application logging and monitoring – enabling software teams and businesses to build fast while having clear insight into their products and applications.

Add ClearInsights Logging with just a few lines of code and automically push new found errors directly to your teams backlog.

 builder.Logging.AddClearInsightsLogger(configuration =>
 {
     configuration.ApiKey = "{ApiKey}";
     configuration.Secret = "{Environment Client Secret}";
     configuration.ApplicationName = "{Application Name}";
 });
ClearInsights community plan is always free for small projects

Leave a Reply