User-Defined Exception

In .NET framework, ApplicationException is originally designed to be the base class of all user-defined exception classes and SystemException is used to be base class of all the system exception thrown by CLR. But there is not significant value if the custom exceptions derived from ApplicationException in practice. Therefore, Microsoft recommends the following.

Note Note
User-defined exception classes should be derived from Exception class instead of ApplicationException class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
using System;

public abstract class MyException : Exception
{
    public abstract void handleIt();
}

public class ExceptionA : MyException
{
    public override void handleIt()
    {
        Console.WriteLine("Handle ExceptionA");
    }
}

public class ExceptionB : MyException
{
    public override void handleIt()
    {
        Console.WriteLine("Handle ExceptionB");
    }
}

public class Program
{
    static void Main()
    {
        testEx(1);
        testEx(2);
        testEx(3);

        Console.Read();
    }

    static void testEx(int i)
    {
        try
        {
            switch (i)
            {
                case 1:
                    test1();
                    break;
                case 2:
                    test2();
                    break;
                case 3:
                    test3();
                    break;
            }
        }
        catch (MyException e)
        {
            Console.WriteLine("Caught in MyException:");
            e.handleIt();
        }
        catch (Exception e)
        {
            Console.WriteLine("Caught in Exception:");
            Console.WriteLine(e.Message);
        }
    }

    static void test1()
    {
        throw new ExceptionA();
    }

    static void test2()
    {
        throw new ExceptionB();
    }

    static void test3()
    {
        DivByZero();
    }

    private static void DivByZero()
    {
        int a = 0;
        int b = 1 / a;  // DivideByZeroException is thrown
    }
}

Output

Caught in MyException:
Handle ExceptionA
Caught in MyException:
Handle ExceptionB
Caught in Exception:
Attempted to divide by zero.

Explanation

  • Line 3-6: Define an abstract MyException class derived from Exception class with an abstract method.
  • Line 8-22: Define 2 sub class inherited from MyException and implemented the abstract method handleIt().
  • Line 52-56: Catch MyExcetpion and run the custom method handleIt().
  • Line 57-61: Catch the other Exceptions and output the error message.
  • Line 66, 71: Throw the custom exceptions and they will be caught in line 52.
  • Line 76: Call DivByZero() to throw a DivideByZeroException which will be caught in line 57.