ASP.NET Basics Part 10: Making Exceptions - The More, the Merrier
(Page 6 of 12 )
Why stop there? ASP.NET also allows you to have multiple "catch" blocks linked to a single "try" block, so that you can handle different exceptions differently. Consider the following example, which demonstrates:
<script language="c#" runat="server">
void
Page_Load()
{
int a, b;
double c;
if(IsPostBack) {
try {
checked {
a =
Convert.ToInt32(Request.Form["num1"]);
b =
Convert.ToInt32(Request.Form["num2"]);
c
=
a/b;
}
output.Text = a.ToString() + " divided by " +
b.ToString()
+ " gives " + c.ToString();
} catch (FormatException fe) {
output.Text = "Can't you read? I asked for
numbers!";
} catch (DivideByZeroException dbze) {
output.Text = "Trying to divide by zero, are
we?";
} catch (OverflowException oe) {
output.Text = "My brain can't handle such large numbers,
give me something smaller";
} catch (Exception e) {
output.Text =
e.Message;
}
}
}
</script>
<html>
<head>
<basefont
face="Arial">
</head>
<body>
<center>
<asp:label
id="output" runat="server" />
<form method="POST"
runat="server">
<table cellspacing="5" cellpadding="5"
border="0">
<tr>
<td>
<font size="1">Gimme a
number...</font>
</td>
<td
align="left">
<asp:textbox id="num1" runat="server"
/>
</td>
</tr>
<tr>
<td>
<font
size="1">Gimme another...</font>
</td>
<td
align="left">
<asp:textbox id="num2" runat="server"
/>
</td>
</tr>
<tr>
<td colspan="2"
align="center">
<input type="submit" name="submit"
value="Enter">
</td>
</tr>
</table>
</form>
</center>
</body>
</html>
In this case, depending on the values entered into the form, ASP.NET will either perform the division, generate a FormatException if the values entered by the user cannot be converted to integers, generate a DivideByZeroException if the denominator is zero, or generate an OverflowException if the numbers involved are too large. The manner in which these exceptions are handled is different – FormatException exceptions will be handled by the first "catch" block, DivideByZeroException exceptions will be handled by the second block, OverflowException exceptions will be handled by the third, and all other exceptions will be handled by the last generic "catch" block.

Incidentally, you can also add a "finally" block to the "try-catch" structure, which contains code that must be executed after the code in the "try" and "catch" blocks. More on this in an upcoming example.
Next: Sending It to the Bitbucket >>
More ASP.NET Articles
More By Harish Kamath (c) Melonfire