Error Handling in Programming

Just like separating out the configuration parameters from the program is important, it is also important to separate the error handling mechanism from general running of the program. There are different ways by which errors are handled by the program.

Errors are of various types. There can be computational errors like Division by Zero, file handling errors like missing files, memory allocation errors and device read or write errors. Depends on the context, an error can be fatal or ignorable. Take for example, if a configuration file is missing, it is a fatal error. The program must terminate and report the error to the user.  Of course, your program can have default values for all the required settings and continue. It is a choice left to the programmers. Some programmers prefer to report the missing file as a warning and continue. Take another example of division by zero. One can always check before the division whether the divisor is zero. If it is a zero, it is reported as an error to the user and the program will continue to work (probably asking for the change in input from the user).

There are various categories of errors and depending on the requirement, we decide what action has to be taken. It is difficult to generalize what must be put in a specific category. But fatal errors normally include the missing of crucial files or libraries, inability to allocate enough memory for computation. There are errors that can be ignored, probably there is a work around for the error. Possible examples include spelling mistakes in a text editor. These are errors with respect to the user, but they don’t have an impact on the software. And often such errors are shown to the user in a light fashioned manner (spelling mistakes underlined red). But spelling mistakes of keywords in a programming language are important errors and can not be ignored, because it will lead to compile time errors. A compiler will return critical errors for such mistakes, but a text editor may not.

Once we have identified the errors and their respective categories, the next step is to determine what action must be taken. The program should

  • Exit
  • Warn the user
  • Signal the user for a change
  • Look for a Workaround
  • Ignore
  • Alert or Email the user
  • Log the errors in a file

So while writing programs, we must

  1. Identify (all) the possible errors
  2. Identify the categories of errors
  3. Action to be taken for every category of error