ASP.NET Basics Part 10: Making Exceptions - All Wrapped Up
(Page 10 of 12 )
Take a close look at this final example on exception handling – it highlights several important concepts that will prove useful when you get down to coding complex business logic in your ASP.NET scripts.
<%@ Import Namespace="System.Data"%>
<%@ Import
Namespace="System.Data.SqlClient"%>
<script Language="C#"
runat="server">
void Page_Load()
{
try {
// build the connection string
string strConn =
"user id=sa;password=;";
strConn += "initial catalog=pubs;data
source=tatooine;";
// create an instance of the SqlConnection
object
SqlConnection objConn = new
SqlConnection(strConn);
try {
// create an instance of the Command
object
SqlCommand objCommand = new SqlCommand("SELECT *
FROM starwars;", objConn);
// open the
connection
objConn.Open();
// populate a SqlDataReader
object
SqlDataReader objReader =
objCommand.ExecuteReader();
// set the source of our "starwars"
datagrid
starwars.DataSource =
objReader;
// bind the data to the
grid
starwars.DataBind();
// close the Reader
object
objReader.Close();
// display output
message
output.Text = "Star
Wars";
} catch (SqlException e) {
throw new Exception("The following error occurred: " +
e.Message);
} catch (Exception e) {
throw new Exception("The following error occurred: " +
e.Message);
} finally {
// close the connection
object
objConn.Close();
}
} catch (SqlException e) {
output.Text = e.Message;
} catch (Exception e) {
output.Text = e.Message;
}
}
</script>
<html>
<title>Star
Wars</title>
<body>
<asp:label id="output" runat="server"
/>
<asp:datagrid id="starwars" runat="server"/>
</body>
</html>
If all goes well, you should see something like this:

However, it's quite likely that something might go wrong - for example, the database connection might not open successfully, or there might be an error in the SQL query. Therefore, the cautious ASP.NET developer always wraps his or her code in multiple "try-catch" blocks, to ensure that exceptions are trapped and resolved.
The example above demonstrates this concept, by nesting multiple "try-catch" blocks within each other. If you were to take out all the business logic from the code listing above, the skeleton would look something like this:
<%
try {
try {
} catch (SqlException e) {
} catch (Exception e) {
} finally {
}
} catch (SqlException e) {
} catch (Exception e) {
}
%>
In this example, the outermost "try-catch" block is used to handle database connection exceptions, while the inner one is used to resolve exceptions in the query and result set.
If a connection cannot be opened to the database server, or if an error occurs in the SqlConnection object, an exception will be raised, which can be caught and handled by the outer "try" block. Here's what the output would look like in this scenario:

But what about the inner "try-catch" block? Well, this handles the SqlCommand and SqlDataReader objects. If, for some reason, you are unable to create these objects - say, the table "starwars" has been deleted by some DBA - you need to inform the user accordingly. This is where the inner block is used, and it generates output like the following:

A couple of interesting things to note in the example above:
1. The inner "try-catch" block throws user-defined exception if an error occurs in query or result set processing using the "throw" statement discussed previously. Since the blocks are nested, exceptions generated in an inner block will be propagated upwards to the parent block, and can be managed by the parent block's "catch" handler.
2. When an exception occurs in the inner block, it implies that an error occurred after the database connection was opened, either during the query phase or the result processing phase. Therefore, when an exception occurs, it becomes necessary to close the database connection before propagating the exception upwards. That's where the inner "finally" block comes in – it contains code that will destroy the SqlConnection object and free up memory associated with the database connection. Since this code is enclosed in a "finally" block, it will be executed without fail.
In case you're wondering - there's no need to do this in the outer "try-catch" block because there's only one possible exception that could occur within the outer block - a failure in opening the database connection. And if the connection can't be opened in the first place, it's pointless having a "finally" block to close it.
Next: Digging Deeper >>
More ASP.NET Articles
More By Harish Kamath (c) Melonfire