Yet another example of when you might want to derive your own Exception class is if you wanted to perform some action-such as logging the event or sending an email to someone at the help desk-every time an exception was thrown. In this case, you would derive your own Exception class and put the needed code in the class constructor, like this: -
using System; public class TestException : Exception { // You would probably have extra methods and properties // here that augment the .NET Exception that you derive from. // Base Exception class constructors. public TestException() :base() {} public TestException(String message) :base(message) {} public TestException(String message, Exception innerException) :base(message, innerException) {} } public class DerivedExceptionTestApp { public static void ThrowException() { throw new TestException("error condition"); } public static void Main() { try { ThrowException(); } catch(Exception e) { Console.WriteLine(e.ToString()); } } }
This code will generate the following output. Note that the ToString method results in a combination of properties being displayed: the textual representation of the exception class name, the message string passed to the exception's constructor, and the StackTrace.
TestException: error condition at DerivedExceptionTestApp.Main()