Exceptions

From Training Material
Revision as of 20:21, 5 February 2013 by Kristian Rother (talk | contribs) (Created page with "{{Cat|Python Commands}} {{Python Links}} == Building failsafe mechanisms == No matter how good your program is, sometimes things will go wrong. However, you can make sure the...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search


Building failsafe mechanisms

No matter how good your program is, sometimes things will go wrong. However, you can make sure they dont blow up in the wrong moment, so that e.g. important data can be saved. Exceptions are the Python mechanism that let you know that something went wrong.

a = raw_input('enter a number')
try:
inverse = 1.0/int(a)
except ZeroDivisionError:
print zero can't be inverted”

#optional
else:
print inverse
finally:
print 'goodbye'

Except, else and finally

Whenever the according kind of error occurs within a try clause, the except code block will be executed. If no exception occurs, the else clause will be executed instead. After any of the two, the code block after finally is executed.

Note that else and finally are required for building subtle cleanup operations after an error. In most situations, they are not neccessary.

Typical Exceptions:

  • ZeroDivisionError – When dividing by zero.
  • KeyError – A key in a dictionary does not exist.
  • ValueError – A type conversion failed.
  • IOError – A file could not be opened.

What exceptions to catch:

Generally, everything that can go wrong even though a program has been written with great diligence, is worth catching.

  • File operations
  • Web operations
  • Database operations
  • User input, especially numbers.

While it is possible to wrap an entire program into a single try.. catch clause, this often makes little sense, because the code gets less transparent and more difficult to debug.