try-except 捕获异常
try:
do some thing
except NameError, e: //若不写NameError表示获取所有异常
print e
猜数字小游戏并使用try except 捕获异常
import random
num = random.randint(0,100)
while True:
try:
guess = int(raw_input("Enter 1~100"))
except ValueError, e:
print "Enter 1~100"
continue
if guess > num:
print "bigger",guess
elif guess < num:
print "small",guess
else:
print 'good'
break
try except 捕获多个错误
try:
do some thing
except NameError, e:
print e
except VauleError, e:
print e
try except else
有异常就执行except
没有异常就执行else
try:
do some thing
except NameError, e:
print e
else:
print e
try finally
如果没有捕获到错误,执行finally
捕获到异常,先执行finally在把错误提交给python解释器
无论是否有异常都会执行finally语句
try except finally
捕获到错误,先处理异常,执行finally
with 语句
raise 和assert
raise [exception[,args]]
exception :异常类
args:描述异常信息的元组
raise IOError , "file wrong"
assert expression [,args]
exoression 表达式,为假时引发异常
assert 7==6,'wrong'
标准异常和自定义异常
- 自定义异常必须继承自标准异常
- 自定义异常只能自己触发
//自定义异常继承自IOError
class FileError(IOError):
pass
raise FileError,'file error '
assert FileError,"file error" //触发异常
网友评论