Python-Ref > Basic usage > Exceptions > Typical usage of exceptions
 
 

<-^^->

Typical usage of exceptions

Exceptions are often used when dealing with user input, because this is the most frequent source of surprising data.
Expand/Shrink
This is an example text in an example file.
It even has
several
lines.
Argumenty příkazové řádky:
python exception2.1.py example.txt
Zdroj: (exception2.1.py)
  1   import sys
  2   
  3   if len( sys.argv) > 1:
  4       filename = sys.argv[1]
  5       try:
  6           f = file( filename, 'r')
  7       except IOError:
  8           print "file not found '%s'" % filename
  9           sys.exit()
 10       print f.read()
 11       f.close()
 12   else:
 13       "give me a filename"
stdout:
This is an example text in an example file.
It even has
several
lines.

Doba běhu: 21.3 ms
Expand/Shrink
Argumenty příkazové řádky:
python exception2.1.py exampl.txt
Zdroj: (exception2.1.py)
  1   import sys
  2   
  3   if len( sys.argv) > 1:
  4       filename = sys.argv[1]
  5       try:
  6           f = file( filename, 'r')
  7       except IOError:
  8           print "file not found '%s'" % filename
  9           sys.exit()
 10       print f.read()
 11       f.close()
 12   else:
 13       "give me a filename"
stdout:
file not found 'exampl.txt'
Doba běhu: 21.4 ms
The following code demonstrates the usage of exceptions in type conversion. It also demonstrates the usage of else in try clauses.
Expand/Shrink
5
6
13.3
20
17.354
X
8
7.65
Zdroj: (exception2.2.py)
  1   f = file( "numbers.2.txt", "r")
  2   
  3   for line in f:
  4       try:
  5           num = float( line.strip())  # we strip the last new-line character
  6       except ValueError:
  7           print "could not convert", line.strip()
  8       else:
  9           print "number", num   # there was no problem
 10   
 11   f.close()
stdout:
number 5.0
number 6.0
number 13.3
number 20.0
number 17.354
could not convert X
number 8.0
number 7.65
Doba běhu: 22.2 ms
The following examples shows the possibility to catch more type of exceptions in one except clause and the ability to get some detail about the exception.
The example below catches all the exceptions in one except clause. There are also two types of ValueError.
Expand/Shrink
 5  2
10  1.53
 7  6
 8  0
 9  3
12  4
13  5
VI  2
 3  2
 3  3  1
 1  5
 
Zdroj: (exception2.3.py)
  1   """this program takes a file that (supposedly) has two numbers per line
  2   and prints the result of division of these numbers.
  3   It tries to catch different types of errors."""
  4   
  5   f = file( "numbers.3.txt", "r")
  6   
  7   for line in f:
  8       try:
  9           a, b = line.split()    # we assume two numbers per line (ValueError)
 10           x = float( a.strip())  # we assume a convertable to float (ValueError)
 11           y = float( b.strip())
 12           result = x / y         # we assume non-zero y (ZeroDivisionError)
 13       except (ValueError, ZeroDivisionError):
 14           print "there is some problem with your numbers '%s'" % line.strip()
 15       else:
 16           print "ok", result   # there was no problem
 17   
 18   f.close()
stdout:
ok 2.5
ok 6.53594771242
ok 1.16666666667
there is some problem with your numbers '8  0'
ok 3.0
ok 3.0
ok 2.6
there is some problem with your numbers 'VI  2'
ok 1.5
there is some problem with your numbers '3  3  1'
ok 0.2
there is some problem with your numbers ''
Doba běhu: 21.3 ms
In order to give the user more clue what is going on, we can catch also the value of the exception.
Expand/Shrink
 5  2
10  1.53
 7  6
 8  0
 9  3
12  4
13  5
VI  2
 3  2
 3  3  1
 1  5
 
Zdroj: (exception2.4.py)
  1   """this program takes a file that (supposedly) has two numbers per line
  2   and prints the result of division of these numbers.
  3   It tries to catch different types of errors."""
  4   
  5   f = file( "numbers.3.txt", "r")
  6   
  7   for line in f:
  8       try:
  9           a, b = line.split()    # we assume two numbers per line (ValueError)
 10           x = float( a.strip())  # we assume a convertable to float (ValueError)
 11           y = float( b.strip())
 12           result = x / y         # we assume non-zero y (ZeroDivisionError)
 13       except (ValueError, ZeroDivisionError), x:
 14           print "error in '%s' (%s)" % (line.strip(), x)
 15       else:
 16           print "ok", result   # there was no problem
 17   
 18   f.close()
stdout:
ok 2.5
ok 6.53594771242
ok 1.16666666667
error in '8  0' (float division)
ok 3.0
ok 3.0
ok 2.6
error in 'VI  2' (invalid literal for float(): VI)
ok 1.5
error in '3  3  1' (too many values to unpack)
ok 0.2
error in '' (need more than 0 values to unpack)
Doba běhu: 21.3 ms