Error Handling

You can and should avoid bugs, but there are runtime errors that cannot be avoided and should be handled as gracefully as possible. You would like to avoid having the end user see ugly or cryptic error messages, or worse, having the application crash. Errors can arise from any number of causes: user action, such as entering invalidly formatted text into a field, program logic errors, or circumstances entirely out of your control, such as an unavailable file or a downed network.

The simplest bugs to find and fix are syntaxerrors: violations of the rules of the language. For example, suppose you had the following line of code in your C# program:

intt i;

When you compile the program, you will get a compiler error because the keyword to declare an integer is misspelled.

Syntax errors are reduced dramatically when using VS2005. Depending on how VS2005 is configured, any code element that isn’t recognized is underlined. If Auto List Members is turned on (Tools Options Text Editor All Languages), the incidence of syntax errors is further reduced.

Should any syntax errors remain or if you are using a different editor, then any syntax errors will be caught by the compiler every time you build the project. It is very difficult for a syntax error to slip by into production code.

Tip

When the compiler finds a syntax error, an error message containing the location of the error and a terse explanation will be displayed in the Output window of VS2005. If the error is caused by something ...

Get Programming ASP.NET, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.