7.7. Creating a New Exception Type
Problem
None of the built-in exceptions in the .NET Framework provide the implementation details that you require for an exception that you need to throw. You need to create your own exception class that operates seamlessly with your application, as well as other applications. Whenever an application receives this new exception, it can inform the user that a specific error occurred in a specific component. This report will greatly reduce the time required to debug the problem.
Solution
Create your own exception class. To illustrate, let's create a custom exception class, RemoteComponentException
, that will inform a client application that an error has occurred in a remote server assembly.
Discussion
The exception hierarchy starts with the Exception
class; from this are derived two classes: ApplicationException
and SystemException
. The SystemException
class and any classes derived from it are reserved for the developers of the FCL. Most of the common exceptions, such as the NullReferenceException
or the OverflowException
, are derived from SystemException
. The FCL developers created the ApplicationException
class for other developers using the .NET languages to derive their own exceptions from. This partitioning allows for a clear distinction between user-defined exceptions and the built-in system exceptions. However, Microsoft now recommends deriving directly from Exception
, rather than ApplicationException
. Nothing actively prevents you from deriving ...
Get C# 3.0 Cookbook, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.