Python的异常处理

来源:互联网 发布:静态网页源码 编辑:程序博客网 时间:2024/05/29 15:48

1.raise语句

为了引发异常,可以使用一个类或者实例调用raise语句。

raise Exception
Traceback (most recent call last):  File "<stdin>", line 1, in <module>Exception


raise Exception('hyperdive overload')
Traceback (most recent call last):  File "<stdin>", line 1, in <module>Exception: hyperdive overload

2.捕捉异常


try:    x=input()    y=input()    print x/yexcept ZeroDivisionError:    print "The second number can't be zero"
2
0
The second number can't be zero

3.捕捉多个异常

上述代码只忽略了除数为0的异常,对于其他的异常,依然会出错



所以,我们可以再添加一个except语句,捕捉类型异常

try:    x=input()    y=input()    print x/yexcept ZeroDivisionError:    print "The second number can't be zero"except TypeError:    print "That wasn't a number..."


或者,在一个except语句里,多添加几个异常

try:    x=input()    y=input()    print x/yexcept(ZeroDivisionError,TypeError,NameError):    print "Your numbers were bogus"


或者,异常全捕捉

try:    x=input()    y=input()    print x/yexcept:    print "Something wrong happend..."


3.如果你希望程序继续运行,但是又想记录下错误,可以捕捉对象


try:    x=input()    y=input()    print x/yexcept(ZeroDivisionError,TypeError,NameError),e:    print e

异常被打印,程序并没有报错

4.添加else字句,当不报错时,执行代码

while True:    try:        x=input()        y=input()        print x/y    except:        print "Invalid input.Please try again."    else:        break




在不报错的时候,退出循环

原创粉丝点击