Structured Exception Handling in .NET
By Vishal Khanna
Programming languages have evolved from ground zero. Days were when errors were handled by simply throwing a message to the end user. Gradually, requirements kept on mounting up, and the need for a robust, intelligent and smooth structure for handling errors cropped up. With the evolution of object oriented programming, the error handling mechanism was piped into classes. Thats what .NET also does. It has structured the complex & cumbersome process of error handling in applications as if its a piece of cake walk.
.NET introduces the concept of structured exception handling. The following components take care of exception handling in .NET:
-
An Exception Class - .NET comprises a series of hundreds of exception classes. Each class specializes with its own set of functionalities, where each exception class is an expert of its own field. Developers may also write their own custom errors.
-
Throwing Member - This member throws an instance of the Exception class to the calling code. This instance is basically an object that comprises all the information related to the properties, members & methods of this exception class.
-
Caller side code 1 - This code piece is at the caller side. It takes care of invoking members that may take care of the exception raised.
-
Caller side code 2 - This piece of code processes the raised exception.
Note that exception classes inherit from the System.Exception base class.
.NET Provides an advanced structure of handling exceptions. The structure is based on the System.Exception class the stands as the backbone of exception handling and is comprised of 4 entities: 1) An Exception Class, 2) a member that throws instance of the exception to the caller, 3) piece of code at the caller to invoke the exception member, 4) piece of code at the caller to handle the exception.
Most of the properties within the System.Exception are readonly. Note that the System.Exception class implements the _Exception interface. The following are the main elements of the System.Exception class:
-
HelpLink - This property returns a URL to a link that contains help related to the exception.
-
InnerException - This returns information about the previous exceptions that caused the current exception.
-
Data - This property returns a collection, that contains information in the form of key-value pairs that provides additional information about the exception.
-
Message - This returns the information about the error in the form of text. It is readonly.
-
Source - This property contains the information about the assembly that invoked the exception.
-
TargetSite - This property returns a MethodBase type, and contains information about the method that has thrown the exception. It is readonly.
-
StackTrace - This property returns the information about the sequence of events that occured the caused the exception. Its extremely useful for debugging purpose.
Throw Keyword - This keyword may be used wh use ten an exception needs to be thrown explicitly. Say you want to throw an exception at a particular threshold value within your application, you may use the throw keyword. See example below:
//Throw exception when Mobile Phone cost exceeds EUR 100.
//Because Pappu cant buy Mobile Phone costing more than EUR 100.
if(iMobilePhoneCost > 100)
{
throw new Exception(string.Format("Exception: Pappu cant buy a mobile phone that costs EUR {0}",iMobilePhoneCost));
}
You just have seen above, how Pappu's application has explicitly thrown the exception.
Try, Catch, Finally Block - The code to be excecuted is placed inside a try block. In case any exception occurs within the try block, the control flow of the application is transferred to the Catch block. The catch block needs to have a parameter that defines the type of exception being passed. In case the exception type matches the parameter in the catch block, the instructions inside this code block are excecuted. Otherwise, the default System.Exception object is called. The finally block is always excecuted in the end, even if the catch block is excecuted.
try
{
//Your geek-like code goes here....
}
catch (Exception ex)
{
//What you want to do if exception is raised, write code here!
}
finally
{
//No matter what happens, this code should excecute!
}
Its worth to note here that usage of appropriate Exception handlers makes sure that the performance of your application is optimized. Blind usage of the main System.Exception class will lead to unnecessary calls within this big class. So make sure to use the precise Exception handler class.
System Level Exceptions - These are those exceptions that are thrown by the Common Language Runtime (CLR). They are fatal errors, and they derive from the System.SystemException class. The System.SystemException class derives from the System.Exception class.
Application Level Exceptions - While creating custom exceptions, the custom exception derives from the System.ApplicationException class, which in turn derives from System.Exception. This exception identifies the cause of the error. So whenever an exception derives from System.ApplicationException, it is not raised by the CLR, rather it is raised by the code inside the created application.
Whats a Generic Catch statement?
C# is powerful. It allows to display generic messages even if no Exception type is caught. See example below:
//Generic catch statement
try
{
// Some code goes here ...
}
catch
{
Response.Write("Pappu doesn't know what is the Exception. But there is something wrong");
}
In order to figure out which are the types of exceptions that may be thrown by a specific base class library, the .NET SDK documentation be be referred.
Happy Programming.
Cheers!