Interview Tips Interview Tips, Interview Questions and Answers

30Dec/100

Throwing and Catching the Custom Exception via C#

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

The final code sample combines the custom exception with the code for a simple console application. This program throws the custom exception within a try block. The exception message is outputted within 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) {}
    }
}
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


No trackbacks yet.