异常处理
- 程序中有可能会出现异常或错误,导致程序终止,使用异常处理,能捕捉到操作信息,方便定位异常位置,通过对异常的预处理可避免程序的崩溃
处理方法
- try except
a=10
b=0
c=a/b
print "done
会抛出异常
a=10
b=0
try:
c=a/b
print c
except ZeroDivisionError,e:
print e.message
print "done"
运行结果:
integer division or modulo by zero
done
捕捉到了异常,并阻止了程序的崩溃 - try except else:当没有异常发生时, else 中的语句会被执行
a=10
b=0
try:
c = b/ a
print c
except (IOError ,ZeroDivisionError),x:
print x
else:
print "no error"
print "done"
运行结果:
0
no error
done raise 引发一个异常
inputValue=input("please input a int data :") if type(inputValue)!=type(1): raise ValueError else: print inputValue
假设输入1.2,运行结果为:
please input a int data :1.2
Traceback (most recent call last):
File “C:/Users/lirong/PycharmProjects/untitled/openfile.py”, line 3, in
raise ValueError
ValueErrortry finally:无论异常是否发生,finally 中的语句都会被执行
a=10 b=0 try: print a/b finally: print "always excute"
运行结果:
Traceback (most recent call last):
always excute
File “C:/Users/lirong/PycharmProjects/untitled/openfile.py”, line 4, in
print a/b
ZeroDivisionError: integer division or modulo by zerofinally 也可以和 except 配合使用
a=10 b=0 try: print a/b except: print "error" finally: print "always excute"
运行结果:
error
always excute
自定义异常类,集成 Exception
```
class MyException(Exception):
def __init__(self,message):
Exception.__init__(self)
self.message=message
a=input("please input a num:")
if a<10:
try:
raise MyException("my excepition is raised ")
except MyException,e:
print e.message
```