A new feature of ASP.Net is the Try/Catch block. If nothing else, it makes
trapping errors much more elegant, and cleaner looking. Whenever your app
encounters an error, it pretty much crashes, with a pretty ugly output for the
end user. Sometimes, the user can understand the resulting page - - sometimes,
not. Here, we will attempt to give you an Overview of the Try/Catch block, in
order to guard against possible code errors.
Naturally, this isn't a way for you to blow off your total development, but
it is a way for you to catch unexpected errors without crashing the actual
execution of the page. You'll still want to check for logical, error-producing
situations, and code around them, depending on your particular application's
circumstances, as well as using ASP.Net Validation Controls.
The Try block, of course, starts with 'TRY'. Then, it ends with 'END TRY'.
Inside this block, you will 'try' or attempt to execute your code. Inside this
block, you'll want to add a 'CATCH' section. Here, this basically tells your
page what to do when it encounters an error. An example of this would be:
Try
' do your code execution here
Catch ex as Exception
lblError.Text = "An error has occured/"
lblError.Text+= ex.Message
End Try
The exception class has several really nice properties, most of which I won't
go into here. Depending on my uses, the most common ways of an exception being
returned are :
- ex.Message - if you want things clean and simple, it shows the basic error
message. - ex.ToString - this gives you much more information, if you want it.
You can also do a basic Catch section (without the 'ex as Exception, as
above). Here, you can use the Error collection, for those of you familiar with
Classic ASP. Err.Number and Err.Description are also available to use in your
Error Trapping.
Lastly, you might want to include a 'FINALLY' section. In this section, you
will want to include code to run, no matter whether the code throws an exception
or whether it runs successfully. This would be a good place to put your
'Closing' code - - Connections, DataReaders, etc. By putting your Conn.Close in
a Finally section, you are assurred of the connection closing at all times.
Also, remember, NOT to Dim any variables (like Connection/DataReader, etc)
inside the Try/Catch block. If you do, they won't be recognized in the 'Finally'
section. You can create your 'execution' code here - - just Dim your connections
etc., outside this block.