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

本文详细介绍Python中的异常处理机制,包括如何引发异常、捕捉异常及自定义异常等,并提供了丰富的示例代码。

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('Enter th 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('Enter th first number:')

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

    print x/y

except(ZeroDivisionError,TypeError,NameError):

    print'Yournumbers were wrong...'

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

try:

    x=input('Enter th first number:')

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

    print x/y

except(ZeroDivisionError,TypeError,NameError),e:

    print e

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

try:

    x=input('Enter th 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语句的习惯。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值