ASP.NET Basics Part 10: Making Exceptions - You Throw(), I'll Catch()
(Page 5 of 12 )
Java programmers have always had the upper hand when it came to handling exceptions in their code, via the well-known (and very clever) "try-catch" exception handling mechanism. Not to be left behind, C# also offer a similar mechanism to ASP.NET programmers. As in Java, you can wrap your code in a "try" block and have exceptions generated by that code resolved through exception-handling routines in one or more corresponding "catch" blocks.
Additionally, you can now use the "throw" construct to artificially induce an exception in your ASP.NET script. This comes in handy, for example, when validating form field data; if the values entered are not in the expected format, you can throw an exception (with an informative error message) and re-direct the user to an error page.
The structure of a "try-catch" block looks like this:
try
{
code block
} catch (Exception1
err1) {
execute this block if exception "err1" is generated
}
catch (Exception2 err1) {
execute this block if exception "err2"
is generated
<P align=left>
<P align=left> ... and so on ...
<P align=left>
<P align=left>}
In order to demonstrate this, let's re-write the previous example to use the "try-catch" exception-handling mechanism:
<script language="c#" runat="server">
void
Page_Load() {
<P align=left>
<P align=left> try {
int a = 19;
int b =
0;
int c = a/b;
} catch(Exception e)
{
message.Text = e.Message + e.StackTrace;
}
}
</script>
<html>
<head></head>
<body>
<asp:label
id="message" runat="server"
/>
</body>
</html>
Here's the output:

Next: The More, the Merrier >>
More ASP.NET Articles
More By Harish Kamath (c) Melonfire