#!/usr/bin/env python
# coding=utf-8
while 1:
print "this is a division program."
c = raw_input("input 'c' continue, otherwise logout:")
if c == 'c':
a = raw_input("first number:")
b = raw_input("second number:")
try:
print float(a)/float(b)
print "*************************"
except ZeroDivisionError:
print "The second number can't be zero!"
print "*************************"
except ValueError:
print "please input number."
print "************************"
else:
break
$ python 21701.py
this is a division program.
input 'c' continue, otherwise logout:c
first number:3
second number:"hello" #輸入了一個不是數(shù)字的東西
please input number. #對照上面的程序,捕獲并處理了這個異常
************************
this is a division program.
input 'c' continue, otherwise logout:c
first number:4
second number:0
The second number can't be zero!
*************************
this is a division program.
input 'c' continue, otherwise logout:4
$
$ python 21701.py
this is a division program.
input 'c' continue, otherwise logout:c
first number:2
second number:0 #捕獲異常
please input rightly.
********************
this is a division program.
input 'c' continue, otherwise logout:c
first number:3
second number:a #異常
please input rightly.
********************
this is a division program.
input 'c' continue, otherwise logout:d
$
while 1:
print "this is a division program."
c = raw_input("input 'c' continue, otherwise logout:")
if c == 'c':
a = raw_input("first number:")
b = raw_input("second number:")
try:
print float(a)/float(b)
print "*************************"
except (ZeroDivisionError, ValueError), e:
print e
print "********************"
else:
break
運行一下,看看提示信息。
$ python 21702.py
this is a division program.
input 'c' continue, otherwise logout:c
first number:2
second number:a #異常
could not convert string to float: a
********************
this is a division program.
input 'c' continue, otherwise logout:c
first number:2
second number:0 #異常
float division by zero
********************
this is a division program.
input 'c' continue, otherwise logout:d
$
在python3.x中,常常這樣寫:except (ZeroDivisionError, ValueError) as e:
#!/usr/bin/env python
# coding=utf-8
while 1:
try:
x = raw_input("the first number:")
y = raw_input("the second number:")
r = float(x)/float(y)
print r
except Exception, e:
print e
print "try again."
else:
break
先看運行結(jié)果:
$ python 21703.py
the first number:2
the second number:0 #異常,執(zhí)行except
float division by zero
try again. #循環(huán)
the first number:2
the second number:a #異常
could not convert string to float: a
try again.
the first number:4
the second number:2 #正常,執(zhí)行try
2.0 #然后else:break,退出程序
$
>>> x = 10
>>> try:
... x = 1/0
... except Exception, e:
... print e
... finally:
... print "del x"
... del x
...
integer division or modulo by zero
del x
看一看x是否被刪除?
>>> x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
當然,在應用中,可以將上面的各個子句都綜合起來使用,寫成如下樣式:
try:
do something
except:
do something
else:
do something
finally
do something
更多建議: