Menu

Robust Software

Exception Handling

Exception handling is a programming technique that lets software deal with unexpected events while a program is running, instead of crashing. The code that deals with the error is often called an error handling routine. Software that copes with these events and keeps working is more robust.

A flowchart: run the try block; if an error occurs jump to the except block and display a message, otherwise the try block finishes; either way the program continues.

How it works in Python 3

The code that might fail is placed inside a try block, and Python runs it as normal. If an error occurs, Python abandons the rest of that block, jumps to the matching except block and runs the instructions there. Without it, the program stops at the error and an error message and traceback are shown.

The except block is where you make the program behave sensibly. It can print a clear message, ask the user to enter the value again, or use a sensible default so the rest of the program still works. For example, a darts scorer might ask how many darts were thrown and use int() to turn the answer into a whole number. If someone types a few, the conversion fails, but an error handling routine can display "Please type a whole number" and carry on scoring. Dividing by zero is another realistic case: if the program works out an average by dividing total points by the number of legs played, and no legs have been played yet, the division fails and the routine can display 0 instead of closing the program.

Exception handling and validation

Validation and exception handling are not the same thing, and robust software often uses both. Validation checks data against criteria before it is used, so bad input is stopped at the door. Exception handling deals with errors that actually occur while the program runs, including ones that validation could not predict, such as a file that has been deleted.

MethodWhen it actsWhat it does
ValidationBefore data is accepted or usedCompares input with rules, such as a booking date that must not be in the past, and rejects anything that fails
Exception handlingWhen an error occurs during executionCatches an error that has already happened and lets the program continue