Errors: Introduction

From Matt Morris Wiki
(Redirected from Errors Introduction)
Jump to navigation Jump to search

Programming - Errors


An "error" takes place when an expected condition is not met. Perhaps a resource cannot be acquired, or a text string cannot be matched to a list of valid codes, or a database transaction cannot get the locks it needs, or a mathematical model cannot be calibrated to the stock market, or the index into a zero-based vector is negative, or ...

Everyone would agree that errors need to be signalled when they occur, and that they need to be handled in an "appropriate fashion".

But people often feel very unsure about how best to do this.

Here some typical problems and questions that people have:

  • I don't know whether to use exceptions or return values
  • Exceptions introduce lots of new potential code paths. Is that bad?
  • What should I put in my error messages?
  • How can we get rid of all the crud in our error messages?
  • We've got Python calling Java calling C++. What do we do with errors?
  • What do I do about checked exceptions in Java?
  • We get exceptions thrown and caught all over the place - it's confusing
  • We're leaking resources when errors take place
  • Throwing exceptions seems to make our app crash
  • Why isn't there more consensus about how to sort out these kinds of issues?

Part of the problem is the way people discuss error handling. It's often done with reference to a single code example of a few dozen lines. This approach fails to shed much light, because a large part of successful error handling is to be able to deal with a problem somewhere far removed from its cause - possibly dozens of function calls away, maybe even in a different language. This kind of behaviour cannot be conveyed by a single snippet of code.

Another part of the problem is the huge variety of systems out there. A distributed, fault-tolerant application will need one kind of error-handling strategy. A PC report script will need another. There is no set of rules that will cover every type of application without a need to apply some thought.

So, here, I'm going to take a different approach. We start with describing what error creation and error handling are trying to achieve. From that we can get some general guidelines. Then we look at good practice for specific languages and situations.