Defensive Coding: Error Handling


As I mentioned, there s always a chance that something unforeseen and out of your control will happen on the journey from quotations file to Web page, so it s wise to build some error handling into the code that reads the file. After all, you don t want your page to spew ugly errors at your users.

For dealing with potential errors, Microsoft Visual Basic .NET provides an elegant solution known as a Try-Catch block. A Try-Catch block is a form of structured exception handling, a way of constructing your code so that it can anticipate run-time problems. In structured exception handling, you define what should happen when a statement can t execute properly. Without structured exception handling, your code simply crashes when it runs into a problem. The following code shows a Try- Catch block used around the statement that opens the text file:

Dim srQuotes As System.IO.StreamReade Try     srQuotes = New System.IO.StreamReader(path &  "\quotations.txt" Catch     labelQuote.Text = "Can t find any quotations, sorry!"     Exit Sub End Try 

Basically, you put the statements you suspect might generate errors after a Try statement so that your program can try to execute them. If the execution succeeds, the program carries on with statements after the End Try statement. But if the execution fails, Visual Basic .NET runs the statements in the Catch block. In this example, we display a friendly error message (instead of the error message that Microsoft ASP.NET would display without the Try-Catch block) and quit the Page_Load subroutine. No harm done.

It s up to you to determine the appropriate statements for the Catch block. In this example, we display an error message. In real life, who knows? Perhaps you wouldn t display anything at all, or perhaps you would jump to another page and display an error there.




Microsoft ASP. NET Web Matrix Starter Kit
Microsoft ASP.NET Web Matrix Starter Kit (Bpg-Other)
ISBN: 0735618569
EAN: 2147483647
Year: 2003
Pages: 169
Authors: Mike Pope
BUY ON AMAZON

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net