Custom Errors in Visual Basic .NET
Custom errors can be implemented in Visual Basic .NET by creating a custom exception class that inherits from the Exception
class. Here’s an example that demonstrates this concept:
Imports System
' A custom error type usually has the suffix "Exception".
Public Class ArgException
Inherits Exception
Public Property Arg As Integer
Public Sub New(arg As Integer, message As String)
MyBase.New(message)
Me.Arg = arg
End Sub
Public Overrides Function ToString() As String
Return $"{Arg} - {Message}"
End Function
End Class
Module Program
Function F(arg As Integer) As Integer
If arg = 42 Then
' Throw our custom exception.
Throw New ArgException(arg, "can't work with it")
End If
Return arg + 3
End Function
Sub Main()
Try
Dim result = F(42)
Catch ex As ArgException
' In VB.NET, we use TypeOf to check the exception type
Console.WriteLine(ex.Arg)
Console.WriteLine(ex.Message)
Catch ex As Exception
Console.WriteLine("err doesn't match ArgException")
End Try
End Sub
End Module
In this example, we define a custom exception class ArgException
that inherits from the Exception
class. This is similar to implementing the error
interface in Go.
The F
function demonstrates how to throw the custom exception when a specific condition is met.
In the Main
subroutine, we use a Try
-Catch
block to handle exceptions. This is equivalent to error handling in Go. The TypeOf
keyword is used to check if the caught exception is of type ArgException
, which is similar to using errors.As
in Go.
To run this program:
$ vbc CustomErrors.vb
$ CustomErrors.exe
42
can't work with it
In Visual Basic .NET, exception handling is used for error management, which is somewhat different from Go’s approach of returning errors. However, the concept of creating and using custom error types remains similar.