ASP.NET Basics Part 10: Making Exceptions - Sending It to the Bitbucket
(Page 7 of 12 )
Now, the "try" statement can only deal with exceptions that it knows about. What about the ones the developer can't predict? Well, it's possible to use the generic keyword "Exception" to handle *any* type of exception generated by the application. The following code snippet illustrates this technique:
<script language="c#" runat="server">
void
Page_Load()
{
<P align=left>
<P align=left> string [] desserts = new string[5];
<P align=left>
<P align=left> try {
// try to access an element which
doesn't exist
desserts[7] = "tiramisu";
} catch
(Exception e) {
<P align=left> // do nothing
}
<P align=left> // carry on with our work
Response.Write("Really,
the dessert was the best part of this meal!");
}
</script>
<html>
<head></head>
<body>
</body>
</html>
In this case, it doesn't matter what type of exception is generated – the generic handler will catch it, ignore it and continue to process the rest of the script. Here's what the output might look like:

It should be noted, however, that this approach, although extremely simple, is *not* recommended for general use. It is poor programming practice to trap all errors, regardless of type, and ignore them; it is far better - and more professional - to anticipate the likely errors ahead of time, and use the "try-catch" construct to isolate and resolve them.
Next: Rolling Your Own >>
More ASP.NET Articles
More By Harish Kamath (c) Melonfire