ASP.NET Basics Part 10: Making Exceptions - Word Games
(Page 2 of 12 )
Normally, when an ASP.NET program encounters an error, be it syntactical or logical, it exits the program at that stage itself with a message indicating the cause of the error. Now, while this behavior is acceptable during the development phase, it cannot continue once an ASP.NET application has been released to actual users. In these live situations, it is unprofessional to display cryptic error messages, which are usually incomprehensible to non-technical users; rather, it is more professional to intercept these errors and either resolve them if resolution is possible, or notify the user with a clear error message if not.
The term "exceptions" refers to those errors which can be tracked and controlled. For example, if a function attempts an unsupported operation on a built-in ASP.NET object (say, trying to run a query on a database server when the database connection itself has failed), ASP.NET will "throw" an exception, together with a stack trace or detailed explanation of the problem. Exceptions like these can be caught by the application, and appropriately diverted to an exception-handling routine.
In order to see what an exception looks like, consider the following simple ASP.NET script, which contains a deliberate error: (trying to access an element of an array which does not exist.)
<script language="c#" runat="server">
void
Page_Load()
{
// create five-element array
string [] desserts = new
string[5];
// try to access the eighth element of the array
desserts[7] =
"tiramisu";
}
</script>
<html>
<head></head>
<body>
</body>
</html>
And its output, which contains an exception:

There are two basic ways of handling ASP.NET exceptions like the one above: the simple way, and the complicated way. The simple way involves redirecting the HTTP client to a generic error page when an exception occurs, and protecting the user from the technical details of the exception by replacing them with a user-friendly error message. This approach has the advantage of being simple to understand and easy to set up; however, it is somewhat inflexible, especially for applications that need more sophisticated exception handling.
That's where the second option comes in. In languages such as C# (my language of choice for the .NET platform), an exception is represented as an instance of the Exception class. This is similar to the Java exception handling model, in which every exception is an instance of an object; in ASP.NET, an Exception object is available to identify and manage exceptions. This Exception object can be used in combination with the "try-catch" exception handling mechanism to trap exceptions in your code and handle them as per your own custom requirements.
Next: Exceptionally Clever >>
More ASP.NET Articles
More By Harish Kamath (c) Melonfire