Exception
In VB.NET programs, many things can go wrong. Sometimes these errors are our fault. Other times, they are unavoidable, inescapable yet potentially harmful.
With Exceptions, we isolate and handle these errors. We use the Try and Catch keywords in the VB.NET language. Exception handling is powerful and convenient.
To begin, we write a small program that tries to divide by zero. We use Integer.Parse
here to avoid a compile-time-error.
DivideByZeroException
. In the Catch block, we display the exception Message.Module Module1 Sub Main() Try ' Try to divide by zero. Dim value As Integer = 1 / Integer.Parse("0") ' This statement is sadly not reached. Console.WriteLine("Hi") Catch ex As Exception ' Display the message. Console.WriteLine(ex.Message) End Try End Sub End ModuleArithmetic operation resulted in an overflow.
An Exception
can be triggered directly by the .NET Framework. But often code will use an explicit Throw-statement. We can specify a message in the Exception
constructor.
Module Module1 Sub Main() Try ' Throw a serious exception. Throw New Exception("Mega-error") Catch ex As Exception ' Display the exception's message. Console.WriteLine(ex.Message) End Try End Sub End ModuleMega-error
NullReferenceException
Strings can be Nothing (null
). If you call a method on a Nothing string
, you will get a NullReferenceException
. You could catch this, with the Catch statement.
Dim value As String = Nothing Console.WriteLine(value.Length)Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.Dim value As String = Nothing If Not value Is Nothing Then Console.WriteLine(value.Length) End If
Try try-catch
construct optionally has a third part. The finally
-statement is always run, except when the program terminates for external reasons.
Console.WriteLine
calls are reached. An exception is triggered in the Try-block.Module Module1 Sub Main() Console.WriteLine(0) Try ' Reached. Console.WriteLine(1) ' An exception is thrown. Dim s As String = Nothing s = s.ToUpper() Catch ex As Exception ' Reached. Console.WriteLine(2) Finally ' Reached. Console.WriteLine(3) End Try Console.WriteLine(4) End Sub End Module0 1 [in Try] 2 [in Catch] 3 [in Finally] 4
Speed is a critical consideration when using exceptions in VB.NET programs. The only fast exception is one that never occurs.
With computers, many things can go wrong. Exception handling isolates error checks in our code. This leads to programs that are still fast, but also simpler to read and maintain.