BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

C# Programming
.NET 1.1+

Throwing Exceptions in C#

The thirty-fifth part of the C# Fundamentals tutorial completes an investigation of exception handling. In this article we will consider the throwing of exceptions to report error conditions. This includes the use of standard and custom exception types.

Custom Exceptions

The .NET Framework provides a rich set of exception types that you can throw and catch. However, the list of available exceptions does not cover every eventuality. Often it is appropriate to define custom exceptions for specific scenarios. This can be achieved by deriving a new exception class from any of the existing types, usually the ApplicationException class.

In the final section of this article we will define a new exception class and demonstrate how it may be thrown and handled. This will be a simple exception with no custom methods or properties. These can be added to the derived class using standard object-oriented programming techniques.

Defining the Custom Exception

Our custom exception will report exceptions whilst printing a page with margins that invalid for the selected printer. To follow naming conventions the new class will be named InvalidPrinterMarginsException. To define the new class within the current namespace and indicate that it is derived from ApplicationException, use the following code:

class InvalidPrinterMarginsException : ApplicationException
{

}

The ApplicationException class provides three basic constructors. The first requires no parameters and creates an exception with default property values. The second accepts a string parameter containing an error message. The final constructor allows a message and an inner exception object to be specified. These three constructors are not automatically inherited by the new exception type so should be added as follows:

class InvalidPrinterMarginsException : ApplicationException
{
    // Use the default ApplicationException constructors
    public InvalidPrinterMarginsException() : base() {}
    public InvalidPrinterMarginsException(string s) : base(s) {}
    public InvalidPrinterMarginsException(string s, Exception ex) : base(s, ex) {}
}

Throwing and Catching the Custom Exception

Once the custom exception is created, it may be thrown and caught in the same way as any other. This includes catching the exact exception or the more types that it is derived from. Indeed, one custom exception may derive from another to create a deep hierarchy of application exceptions for flexible error handling.

The final sample combines the custom exception with the code for a console application. This program throws the custom exception within a try block. The exception message is outputted by the following catch block.

using System;

namespace BlackWasp
{
    class TestApp
    {
        static void Main(string[] args)
        {
            try
            {
                // Throw a test exception
                throw new InvalidPrinterMarginsException ("The margins are too small");
            }
            catch (InvalidPrinterMarginsException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }

    // Custom exception class
    class InvalidPrinterMarginsException : ApplicationException
    {
        // Use the default ApplicationException constructors
        public InvalidPrinterMarginsException() : base() {}
        public InvalidPrinterMarginsException(string s) : base(s) {}
        public InvalidPrinterMarginsException(string s, Exception ex) : base(s, ex) {}
    }
}

A Final Note on ApplicationException

When Microsoft created the .NET framework they defined two base classes. These were for system-defined exceptions (SystemException) and custom exceptions (ApplicationException). On reviewing this segregation, Microsoft realised that the benefits of such a structure were not as expected. For this reason, Microsoft now advises you to derive custom exceptions directly from the Exception class. This keeps the hierarchy of exceptions flatter. The ApplicationException remains a part of the .NET framework for backwards compatibility at the time of writing.

9 April 2007