ASP.NET Exceptions 101 for .NET: What and Why - ' Structured Exception Handling to ' (
Page 3 of 5 )
the Rescue">
Structured Exception Handling to the Rescue
Structured exception handling picks up where numeric error reporting leaves off. Instead of passing numeric error codes out of your method to indicate error, you throw an exception.
ADVERTISEMENT
An exception is a class fundamental to .NET. .NET comes with a variety of exception classes that derive from the base class, System.Exception. Also note that an exception is a class, meanig that you can inherit from existing exception classes to make custom exceptions to suit your own needs.
An exception is self describing. Because an exception is a class, it has a name — its type name. Simple enough. Whereas, in a numeric error coding system, you need some sort of lookup table mechanism to figure out the meaning of the numeric error code, with exceptions the semantic meaning of the exception is built into the name.
For example, there is little doubt as to what exceptions such as OutOfMemoryException, OverflowException, or InvalidCastException are about.
Figure 2: Structured Exception Handling allows for more robust applications.
A thrown exception tells your program that your code has violated a programmatic interface's implicit assumptions. In other words, something has gone wrong. Whenever an exception is thrown, your program will abort unless the exception is caught and "handled." In .NET, you handle exceptions within a try ... catch ... finally statement, as shown below in Listing 4. The example illustrates the use of a fictitious CreditCard object that contains a method called MakePayment(). MakePayment() uses custom exceptions do indicate failure.
Listing 4: Credit card information is passed into the CreditCard object in its constructor.
class ExceptionsApp
{
///
/// The main entry point for the application.
///
[STAThread]
static void Main(string[] args)
{
//
// TODO: Add code to start application here
//
CreditCard cc = new CreditCard("Dick","Tracy",
"1234123412341234",
102.50,
Convert.ToDateTime("12/1/2006"));
string Code = string.Empty;
try
{
Code = cc.MakePayment();
}
catch(InvalidCardNumberException ex)
{
Console.Write("Credit Card Number is invalid");
}
catch(CardExpiredException ex)
{
Console.Write("Credit Card has expired");
}
catch(OverCreditLimitException ex)
{
Console.Write("The customer has exceeded his credit limit.");
}
catch(SeizeCardException ex)
{
Console.Write("Danger: Destroy the card and call 800.444.1234");
}
catch
{
Console.Write("Unknown system error.");
}
Console.Write("Transaction successful. Authorization code: " + Code );
}
}
}
The method MakePayment() is a member of the fictitious CreditCard object. CreditCard.MakePayment() throws custom errors that are derived from the .NET exception class. (Download the code project that ships with this article to see the details of custom exceptions.