Trapping Errors and Exceptions in ASP.Net
As most programmers know handling errors is one of the biggest caveats in softwareapplication development. At times exception handling can be laborious but, it isfundamental to ensure that your applications perform as expected.
This being said in ASP.Net we use the TRY/CATCH/FINALLY Block to handle errors andexceptions in web development. This allows us to make error trapping more elegant,than just the regular ASP.Net generic error. At some point in the life of your application it will encounter an error or crash. End Users may be able to interpret the error and tell you what it means, but normally this is not the case.
Using this methodology you can catch unexpected errors without having to sacrifice theexecution of the page completely. As a programmer you will still need to check forsyntax, run-time, and logical errors and code around them. In addition you may also what to use the .NET Validation Controls to make sure you are getting the correct input for your controls.
As previously stated the TRY/CATCH/FINALLY Block begins with “TRY”. It end’s with “END TRY” Inside the block you will “try” to execute some piece of code. While in the block you will also want to add a “CATCH”statement. What the “catch” statement does is tells your page what it should if it encounters an error.
Example:
Try
‘execute something
Catch ex As Exception
lblerror.Text = “An error has occured/”
lblerror.Text += ex.Message
End Try
There are a couple of different ways to use the exception class.
-ex.Message- shows the basic error message
-ex.ToString- this will give you additional information
The final step in error handling is to add the “FINALLY” statement.Here you want to add the code that will run regardless if the code throws and exception, or if it ran as expected. This would be a good place to put “Closing” code foryou app, Conn.Close
These are the basics of Error Trapping.
Enjoy
Keidrick Pettaway works as Systems Administrator / Web Developer at The University of South Alabama Library.
Feel Free to contact via his website at http://www.kpettaway.com
Article from articlesbase.com
Find More ASP.NET Articles