Main Content

Exceptions - a fail-safe way of trapping things that may go wrong

Archive - Originally posted on "The Horse's Mouth" - 2011-09-11 16:51:48 - Graham Ellis

As part of a previous post, I was looking at the "Internal Server Errors" logged on our web server over the past 3 months ... and I found one coming from a Python / CGI demonstration which I wrote and uploaded for a delegate a couple of months back.

Internal server error 500 (by default on Apache httpd) gives little away to the web site visitor - it just says "this page is broken" really. And that's sensible - by displaying more data, it could give the recipient of the error message clues as to the structure, and thus possible weaknesses, or the web site. However, the error message will have been logged in the server's error log file so that the developer / web site admin / maintainer can go back and find out a little more.

It turned out that the server error was being reported when script was called up directly rather than via the form that was intended to go with it, and so it tried to match a regular expression in a variable that wasn't a string. The failure was in

  strikes = words.findall(fill["stuff"])

The first (and obvious) thought is "let's add a test to make sure that doesn't happen again". But to do so would fix the immediate problem without giving consideration to any other problems that might occur. In other words - adding a test is not fail safe. What I have elected to do instead is to catch an exception. Catching an excpetion lets me deal with all the things that might go wrong in the regular expression match, including those I haven't even though of. So it IS a fail safe approach. Here is the code with the exception handler added:

  try:
    strikes = words.findall(fill["stuff"])
  except:
    strikes = ["'no input'"]


The form is [here] and the (now modified) complete script is [here].

On last week's Ruby Programming Course, we also looked at exceptions. There's a nice, several stage example in the course notes that shows ...
• An example which will crash is the file does not exist - [here]
• The same example, but with any errors which are encountered being rescued - [here]
• A final example of exceptions, showing how you can segment different exception types into different handlers, yet still have the safety net of all exceptions being caught. Source code [here].