VB.Net Examples of User-Defined Exceptions?

18,146

The basic requirement is that you add a new class to your project that inherits from the built-in class System.Exception. That gets you almost everything you need for free, because it's all implemented inside of the System.Exception class.

The only thing you need to add to the class file are the constructors (because, remember, constructors are not inherited). While you don't have to define all three standard constructors, I highly recommend that you do so, just so that your interface is consistent with all of the exception classes provided by the .NET Framework. It's not that hard to just define them once, and recommended by code analysis tools.

And finally (this is the step forgotten by most people, including by those people who posted the other answers to this question), you need to make your exception serializable. Do that by adding the SerializableAttribute to the class declaration and by adding a Protected constructor that is used internally by the serialization mechanism. The attribute is not inherited from System.Exception, and must be stated explicitly.

Since you asked so nicely, here's a complete example, with all of the above implemented:

''' <summary>
''' The exception that is thrown when DWM composition fails or is not
''' supported on a particular platform.
''' </summary>
<Serializable()> _
Public Class DwmException : Inherits System.Exception

    ''' <summary>
    ''' Initializes a new instance of the <see cref="DwmException"/> class.
    ''' </summary>
    Public Sub New()
        MyBase.New()
    End Sub

    ''' <summary>
    ''' Initializes a new instance of the <see cref="DwmException"/> class
    ''' with the specified error message.
    ''' </summary>
    ''' <param name="message">The message that describes the error.</param>
    Public Sub New(ByVal message As String)
        MyBase.New(message)
    End Sub

    ''' <summary>
    ''' Initializes a new instance of the <see cref="DwmException"/> class
    ''' with the specified error message and a reference to the inner
    ''' exception that is the cause of this exception.
    ''' </summary>
    ''' <param name="message">The message that describes the error.</param>
    ''' <param name="innerException">The exception that is the cause of the
    ''' current exception, or a null reference if no inner exception is
    ''' specified</param>
    Public Sub New(ByVal message As String, ByVal innerException As System.Exception)
        MyBase.New(message, innerException)
    End Sub

    ' Constructor required for serialization
    <SecuritySafeCritical()> _
    Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)
        MyBase.New(info, context)
    End Sub

End Class

Ahh, after posting the above, I realized that I might have completely misinterpreted your question. I (and the other answers) thought you were asking for an example of how to implement a user-defined exception class. It looks like you're just asking of examples when you would do such a thing in your own project... That's much trickier.

Most of the time, you don't want to do this. The only time you should throw a custom exception is when you're writing a reusable code library (like a .DLL file), and you expect the client code to react differently based on the particular exception that was thrown. So, in my case, I throw a DwmException from my class library because the client application might want to catch that exception and disable some fancy UI feature when DWM composition is not enabled on the user's computer. Ordinarily, I would just throw a standard NotSupportedException, but in this case, I want to provide the client with the ability to distinguish between an exception they can handle and one that they can't or shouldn't.

In a standard application, where all the code is self-contained (i.e., when you are not creating a reusable library of code), you should basically never create/throw a custom exception. Throw one of the standard ones, instead. Following the above rule, if you needed to throw a custom exception to affect how the client code reacted, that would be an indication that you're using exceptions for "flow control" inside of your app (since the producer and the consumer are one in the same), which is strongly discouraged.

Share:
18,146
Ryan James
Author by

Ryan James

Updated on June 09, 2022

Comments

  • Ryan James
    Ryan James almost 2 years

    Very simply put, I am wondering if anybody here can give me an example of a user-defined exception in VB.Net. I already have two examples that I was able to find online, but other than that, I cannot think of any more. I need to find at least 5 to put in my notes, and then submit to my teacher.

    The two I have so far are: invalid login information (such as improper username or password), and expired credit card information on an online store. Any help would be greatly appreciated.

  • Oliver
    Oliver about 6 years
    Please could you explain why we need to make exception serializable?
  • Ama
    Ama about 5 years
    Should it inherit from System.Exception, or from SystemException? The documentation says SystemException "Serves as the base class for system exceptions namespace".
  • Cody Gray
    Cody Gray about 5 years
    @Ama It should not derive from SystemException unless you're actually part of the system. Application exceptions are just subclasses of Exception. SystemException is a wrapper around the HRESULT COR_E_SYSTEM.
  • Ama
    Ama about 5 years
    Not sure what HRESULT and COR_E_SYSTEM are, but I understand that's dedicated for System-related Exceptions. Then, the natural subsequent question is: what about System.AppliationException ? Does it change anything? Are there some thin subtilities I should not really worry about given I am not developping anything super Fancy (a VSTO)?
  • Ama
    Ama about 5 years
    According to the Microsoft Doc, Try ... Catch ex as ArithmeticException will catch ArithmeticException but also all the Exceptions that inherited from it, such as DivideByZeroException. This is extremely usefull when wanting to handle specific groups of Exceptions, and I beleive for most of the time Custom Exceptions should be derived from ApplicationException to offer that flexibility.