您的位置:首页 > 编程语言 > Python开发

Python学习笔记(八)异常

2014-02-03 16:43 459 查看
8异常

8.1什么是异常

Python用异常对象来表示异常情况。每一个异常都是一些类的实例,这些实例可以被印发,并且可以用很多种方法进行捕捉并且对其进行处理,而不是让整个程序失败。

8.2按自己的方式出错

8.2.1raise语句

为了引发异常,可以使用一个类(可以是Exception的子类)或者实例参数调用raise语句。

raise Exception
 
Traceback (mostrecent call last):
  File "<pyshell#0>", line 1,in <module>
    raise Exception
Exception
>>> raiseException('a exception happened')
 
Traceback (mostrecent call last):
  File "<pyshell#1>", line 1,in <module>
    raise Exception('a exception happened')
Exception: aexception happened


第一个例子引发了一个没有任何错误信息的普通异常,后一个例子中则添加了一些错误信息。

8.2.2自定义异常类

就像其他类一样,只要确保从Exception类继承,那么编写一个自定义异常类基本上就像下面那样:

8.3捕捉异常

为了捕捉异常并且做一些错误处理,可以这样写程序:

>>> x=1
>>> y=0
 
 
>>>
try:
    x/y
exceptZeroDivisionError:
    print ("can not division 0")
   
   
can not division 0


如果捕捉到了一个异常,又想重新引发它那,那么可以调用不带参数的raise。 通过这一点也可以实现一种屏蔽功能,例如ZeroDivisionError,在功能激活时屏蔽这个异常。

下面是这样一个类的代码:

classMuffledCalculator:
   run=False
   def calc(self,expr):
       try:
           return eval(expr)
       except ZeroDivisionError:
           if self.run:
                print("somethingwrong")
           else:
                raise


用法实例:

a=MuffledCalculator()
>>> a.calc('10/2')
5
>>> a.calc('10/0')
 
Traceback (most recent call last):
 File "<pyshell#5>", line 1, in <module>
   a.calc('10/0')
 File "C:\Users\LTianchao\Desktop\python\5.py", line 5, in calc
   return eval(expr)
 File "<string>", line 1, in <module>
ZeroDivisionError: integer division ormodulo by zero
>>> a.run=True
>>> a.calc('10/0')
something wrong


8.4 不止一个except语句

可以在同一个try/except语句后加另一个except语句:

class MuffledCalculator:
    run=False
    def calc(self,expr):
        try:
            return eval(expr)
        except ZeroDivisionError:
            if self.run:
                print("somethingwrong")
            else:
                raise
        except TypeError:
           print("somethin wrong")


8.5也可以用同一个块捕捉多个异常

如果需要使用一个块捕捉多个异常,那么可以将它们作为元祖列出:

try:
    x=input()
    y=input()
    print(x/y)
except(ZeroDivisionError,TypeError):
print("something is wrong")


8.6捕捉对象

如果想在except中访问异常对象本身:比如希望程序继续执行,又想把异常记录下来:

try:
    x=int(input())
    y=int(input())
    print(eval('x/y'))
except(ZeroDivisionError,TypeError)as e:
print(e)
 
>>>
1
0
division by zero


8.7真正的全捕捉

在except子句中忽略所有异常类,就可以捕捉所有异常

try:
    x=int(input())
    y=int(input())
    print(eval('x/y'))
except:
print("something is wrong")


但是这样做非常危险,它会隐藏程序员未想到并且未做好准备处理的错误。

8.8else子句

while True:
    try:
        x=int(input())
        y=int(input())
        print(x/y)
    except:
        print("please input again")
    else:
        break
>>>
1
0
please input again
1
1
1.0


8.9最后。。

最后,是finally子句。他可以用来在可能的异常后进行清理。它和try语句联合使用:

x=None
try:
    x=1/0
finally:
    print("clean up")
del x


小结

异常对象

警告

引发异常

自定义异常类

捕捉异常

else子句

finally
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: