Simple exception handling example. : except « Statement « Python Tutorial






number1 = raw_input( "Enter numerator: " )
number2 = raw_input( "Enter denominator: " )

# attempt to convert and divide values
try:
   number1 = float( number1 )
   number2 = float( number2 )
   result = number1 / number2

# float raises a ValueError exception   
except ValueError:
   print "You must enter two numbers"

# division by zero raises a ZeroDivisionError exception   
except ZeroDivisionError:
   print "Attempted to divide by zero"

# else clause's suite executes if try suite raises no exceptions
else:
   print "%.3f / %.3f = %.3f" % ( number1, number2, result )








3.10.except
3.10.1.Catching Two Exceptions
3.10.2.Simple exception handling example.
3.10.3.Demonstrating exception arguments and stack unwinding.
3.10.4.Catch more than on exceptions
3.10.5.Catch KeyError and AssertionError
3.10.6.try/except block that checks for correct user input
3.10.7.try/except block with string argument