ASP.NET Basics Part 10: Making Exceptions - Rolling Your Own
(Page 8 of 12 )
Thus far, you've been working with ASP.NET's built-in exceptions, which can handle most logical or syntactical expressions. However, ASP.NET also allows you to get creative with exceptions, by generating your own custom exceptions if the need arises.
This is accomplished via the "throw" statement, which is used to raise errors which can be detected and resolved by the "try" family of exception handlers. The "throw" statement needs to be passed an exception name, and an optional descriptive string. When the exception is raised, this exception name and description will be made available to the defined exception handler.
<script language="c#" runat="server">
void
Page_Load()
{
if(IsPostBack)
{
check_user(Request.QueryString["name"]);
}
}
void check_user(string name) {
if(name == "Neo")
{
Response.Write("Welcome to The Matrix, " + name +
"!");
} else {
throw new Exception("Access
denied to The Matrix. Try
again.");
}
}
</script>
<html>
<head>
<basefont
face="Arial">
</head>
<body>
<center>
<form
method="GET" runat="server">
<table cellspacing="5" cellpadding="5"
border="0">
<tr>
<td>
<font size="1">Name, rank
and serial, number, soldier!</font>
</td>
<td
align="left">
<asp:textbox id="name" 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, if the name entered in the text box is not "Neo", ASP.NET will raise a user-defined exception with a string of text describing the nature of the error. Take a look:

Trapping user-defined exceptions is exactly the same as trapping pre-defined ASP.NET exceptions. The following refinement of the code above illustrates this:
<script language="c#" runat="server">
void
Page_Load()
{
if(IsPostBack) {
try
{
check_user(Request.QueryString["name"]);
}
catch (Exception e) {
output.Text =
e.Message;
}
}
}
<P align=left>
void check_user(string name) {
if(name == "Neo")
{
output.Text = "Welcome to The Matrix, " + name +
"!";
} else {
throw new Exception("Access
denied to The Matrix. Try
again.");
}
}
</script>
<html>
<head>
<basefont
face="Arial">
</head>
<body>
<center>
<asp:label
id="output" runat="server" />
<form method="GET"
runat="server">
<table cellspacing="5" cellpadding="5"
border="0">
<tr>
<td>
<font size="1">Name, rank
and serial, number, soldier!</font>
</td>
<td
align="left">
<asp:textbox id="name" runat="server"
/>
</td>
</tr>
<tr>
<td colspan="2"
align="center">
<input type="submit" name="submit"
value="Enter">
</td>
</tr>
</table>
</form>
</center>
</body>
</html>
Here's the output of the script above, when the wrong username is entered.

Next: Meeting the Family >>
More ASP.NET Articles
More By Harish Kamath (c) Melonfire