14. Python脚本学习笔记十四异常

来源:互联网 发布:vue js 折叠面板例子 编辑:程序博客网 时间:2024/05/29 19:22

14. Python脚本学习笔记十四异常

                  本篇名言:“用快乐带动心情,用观念导航人生,用执着追求事业,用真诚对待朋友,用平淡对待磨难,用努力追求幸福,用感恩对待生活!”

                  编写程序的时候,需要辨别事件的正常过程和异常。

                  Python用异常对象来表示异常情况。遇到错误后,会引发异常。如果异常对象未被处理或捕捉,程序就会用所谓的回溯终止执行。  

1.  引发异常

1.1      Raise语句

手动引发异常,如下:

>>>raise Exception

Traceback (mostrecent call last):

  File "<stdin>", line 1, in<module>

Exception

又如下:

>>> raiseException("oh,sorry")

Traceback (most recent call last):

 File "<stdin>", line 1, in <module>

Exception: oh,sorry

1.2      内建异常

内建异常都可以再exceptions模块中找到。查看如下:

>>>import exceptions

>>>dir(exceptions)

['ArithmeticError','AssertionError', 'AttributeError', 'BaseException', 'Buffer

Error','BytesWarning', 'DeprecationWarning', 'EOFError', 'EnvironmentError', 'E

xception','FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'I

mportError', 'ImportWarning','IndentationError', 'IndexError', 'KeyError', 'Key

boardInterrupt','LookupError', 'MemoryError', 'NameError', 'NotImplementedError

', 'OSError','OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'R

untimeError','RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError',

 'SyntaxWarning', 'SystemError', 'SystemExit','TabError', 'TypeError', 'Unbound

LocalError','UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'Unicod

eTranslateError','UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'Win

dowsError','ZeroDivisionError', '__doc__', '__name__', '__package__']

 

我们可以raise其中的的异常如下:

>>> raise ArithmeticError

Traceback (most recent call last):

 File "<stdin>", line 1, in <module>

ArithmeticError

看下最重要的内建异常类如下:

 

1.3      自定义异常

可以编写一个自定义异常类基本上像下面:

ClassSomeCustomException(Exception):pass

2.  捕捉异常

如下使用try进行捕捉

try:

    x=input('Enterth first number:')

    y=input('Enter the second number:')

    print x/y

exceptZeroDivisionError:

    print"Thesecond number can not be zero!"

输出如下:

Enterth first number:10

Enterthe second number:0

The secondnumber can not be zero!

 

                  如果没有捕捉异常,它就会被传播到调用的函数中。如果在那里依旧没有捕获,异常就会浮到程序的最顶层。

                  如果不在此处处理,可以直接调用raise进行异常传递。

 

同时捕捉多个异常,可以用如下代码,如下:

try:

    x=input('Enterth first number:')

    y=input('Enter the second number:')

    print x/y

except(ZeroDivisionError,TypeError,NameError):

    print'Yournumbers were wrong...'

如果需要访问异常对象本身:

try:

    x=input('Enterth first number:')

    y=input('Enter the second number:')

    print x/y

except(ZeroDivisionError,TypeError,NameError),e:

    print e

捕捉所有异常,可以使用如下,不过这样比较危险,会隐藏所有程序员未想到并且未做好准备处理的错误。

try:

    x=input('Enterth first number:')

    y=input('Enter the second number:')

    print x/y

except:

    print"error"

else:

    print"ok"

 

学过JAVA的伙伴肯定知道finally,finally 子句不管是否发生异常都会执行。

 

 

3.  小结:

异常处理并不是很复杂。通过添加try/except或者 try/finally语句进行处理。在很多情况下,使用try/except 语句比使用if/else会更自然一些,应该养成尽可能使用try/except语句的习惯。

 

阅读全文
0 0