The exception handling mechanism is introduced so that the running program does not crash when an error occurs.
Common formats:
Try:command 1except:command 2
When command 1 performs an error, command 2 is executed. Command 2 is usually a self-defined error message or a system default prompt.
eg
#!/usr/bin/pythonwhile 1: c = raw_input ("Input ' C ' continue,otherwise logout: ") if c == ' C ': a = raw_input ("Input first number:") b = raw_input ("Input second number:") try: print float (a)/float (b) print "+ + ++++++++++++++++++ " &nbSp; except zerodivisionerror : print "The second number can ' t be zero!" print "++++++++++++++++++++" except ValueError: print "Please input number." print "++++++++++++++++++++" else: break
The first except or the second except statement is executed when the second entered by the user is 0 or is not a number.
Other formats:
Try:command 1except:command 2else:command 3
When command 1 is executed successfully, command 3 is executed and command 2 is not executed. If command 1 executes an exception, then command 2 is executed, and command 3 is not executed.
Try:command 1except:command 2else:command 3finally:command 4
In this format, finally (Command 4) is always executed regardless of which statement is executed.
Python bit record 12: Exception handling