You are a guest. Restricted access. Read more

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

python/exceptions.txt · Last modified: 2013/04/14 16:52 (external edit)
Back to top
CC Attribution-Share Alike 3.0 Unported
chimeric.de = chi`s home Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0