Errors and Exceptions


Before we start with the practicalities of dealing with errors, we need to understand a couple of terms. We tend to use the word "error" for most things that go wrong, but there's a difference between things that we know can go wrong, and the unexpected. There are three general types of errors:

  • Syntactic errors – these are found in code that violates the grammar rules of the programming language, and are detected and reported by the compiler.

  • Semantic errors – these occur in code that follows the rules and compiles, but doesn't work as intended.

  • Input errors – these occur when our program gets bad information that it doesn't know how to handle.

You might think that if we know something can go wrong then we can prevent it, but that's not always the case. For example, take user input. We can't control what the user is going to type, so we have to check their input to make sure it's in a format we're able to accept.

The flip side of this is dealing with the unexpected – exceptions. For example, when dealing with disk files, we might write our program so that it assumes it has permissions to read them, but what if it doesn't? That's an exceptional situation, but it's one we need to allow for. Likewise, when dealing with databases we expect the database to be available, but what if it isn't? What if the system administrator has mistakenly kicked the plug and switched off a whole rack of machines (don't laugh, it happened to me once!). That's an exceptional situation, but one that's certainly conceivable.

So there are two sides to this story – an error is a generic term that describes something going wrong. An exception, a term to describe the unexpected, is what .NET calls an unexpected event. If something goes wrong in the code, an exception is raised – think of this like giving a lecture, and one of the students raising their hand to ask a question. In the case of .NET, the system raises its hand to say "Something has gone wrong". We can use special code to watch out for these exceptions, and thus take some appropriate action, interrupting the flow of the 'lecture' to deal with the interruption, before hopefully resuming where we left off. This is called catching an exception, and we'll look at that later.

When programming, we never assume that anything is going to work, so we build in defenses to prevent errors and exceptions that would crash our page.




Beginning Dynamic Websites with ASP. NET Web Matrix
Beginning Dynamic Websites: with ASP.NET Web Matrix (Programmer to Programmer)
ISBN: 0764543741
EAN: 2147483647
Year: 2003
Pages: 141

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