Export (0) Print
Expand All

Using User-Defined Exceptions

If you want users to be able to programmatically distinguish between some error conditions, you can create your own user-defined exceptions. The .NET Framework provides a hierarchy of exception classes ultimately derived from the base class Exception. Each of these classes defines a specific exception, so in many cases you only have to catch the exception. You can also create your own exception classes by deriving from the ApplicationException class.

When creating your own exceptions, it is good coding practice to end the class name of the user-defined exception with the word "Exception." It is also good practice to implement the three recommended common constructors, as shown in the following example.

Note   In situations where you are using remoting, you must ensure that the metadata for any user-defined exceptions is available at the server (callee) and to the client (the proxy object or caller). For example, code calling a method in a separate application domain must be able to find the assembly containing an exception thrown by a remote call. For more information, see Best Practices for Handling Exceptions.

In the following example, a new exception class, EmployeeListNotFoundException, is derived from System.ApplicationException. Three constructors are defined in the class, each taking different parameters.

Imports System
Public Class EmployeeListNotFoundException
   Inherits ApplicationException
   Public Sub New()
   End Sub 'New
   Public Sub New(message As String)
   End Sub 'New
   Public Sub New(message As String, inner As Exception)
      MyBase.New(message, inner)
   End Sub 'New
End Class 'EmployeeListNotFoundException
using System;
public class EmployeeListNotFoundException: ApplicationException
   public EmployeeListNotFoundException()
   public EmployeeListNotFoundException(string message)
      : base(message)
   public EmployeeListNotFoundException(string message, Exception inner)
      : base(message, inner)

See Also

Using the Try/Catch Block to Catch Exceptions | Using Specific Exceptions in a Catch Block | Best Practices for Handling Exceptions | Exception Handling Fundamentals

© 2014 Microsoft