CHAPTER 7 UNDERSTANDING STRUCTURED EXCEPTION HANDLING
System-Level Exceptions (System.SystemException)
The .NET base class libraries define many classes that ultimately derive from System.Exception. For
example, the System namespace defines core exception objects such as ArgumentOutOfRangeException,
IndexOutOfRangeException, StackOverflowException, and so forth. Other namespaces define exceptions
that reflect the behavior of that namespace. For example, System.Drawing.Printing defines printing
exceptions, System.IO defines input/output-based exceptions, System.Data defines database-centric
exceptions, and so forth.
Exceptions that are thrown by the .NET platform are (appropriately) called system exceptions. These
exceptions are generally regarded as nonrecoverable, fatal errors. System exceptions derive directly from
a base class named System.SystemException, which in turn derives from System.Exception (which
derives from System.Object):
public class SystemException : Exception
{
// Various constructors.
}
Given that the System.SystemException type does not add any additional functionality beyond a set
of custom constructors, you might wonder why SystemException exists in the first place. Simply put,
when an exception type derives from System.SystemException, you are able to determine that the .NET
runtime is the entity that has thrown the exception, rather than the code base of the executing
application. You can verify this quite simply using the is keyword:
// True! NullReferenceException is-a SystemException.
NullReferenceException nullRefEx = new NullReferenceException();
Console.WriteLine("NullReferenceException is-a SystemException? : {0}",
nullRefEx is SystemException);
Application-Level Exceptions (System.ApplicationException)
Given that all .NET exceptions are class types, you are free to create your own application-specific
exceptions. However, due to the fact that the System.SystemException base class represents exceptions
thrown from the CLR, you might naturally assume that you should derive your custom exceptions from
the System.Exception type. You could do this, but you could instead derive from the
System.ApplicationException class:
public class ApplicationException : Exception
{
// Various constructors.
}
Like SystemException, ApplicationException does not define any additional members beyond a set
of constructors. Functionally, the only purpose of System.ApplicationException is to identify the source
of the error. When you handle an exception deriving from System.ApplicationException, you can
assume the exception was raised by the code base of the executing application, rather than by the .NET
base class libraries or .NET runtime engine.
266