# JythonTutorial:Exceptions

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Contents

# Exceptions

Python error reporting is based on "exceptions". Let us consider an example in which we assign a to 8, b to 0, and then we will try to divide these numbers. In case of falure, we will do something else (for example, print a message).

a,b=8,0
try:
c=a/b
except ZeroDivisionError:
print "divide by zero"

Run this example. What do you see? One question is : how do you know which exception to use. In the above example, it was "ZeroDivisionError", which is rather obvious. But in a more complicated code, you may not know befohend what may go wrong with your program. In this case, just use "except", and it will catch all errors that could possibly be generated. Let us consider another example:

a,b=8,0
c=0
try:
c=a/b
except:
c=-1
print c

You can also make your code completely silent, without doing anything in case of a problem:

a,b=8,0
c=0
try:
c=a/b
except:
pass
print c

A general structure of the exceptions is:

try:
# perform a task that may raise an exception
except Exception, value:
# perform exception handling
finally:
# perform a task that must always be completed. It will be performed before the exception