Python,异常 exception

同Java一样,Pyton异常对象来表示异常情况。遇到错误后,引发异常,如果异常对象并未对处理或捕捉,程序就会用所谓的回溯(Traceback)来终止执行;

>>> 1/0

Traceback (most recent call last):

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

ZeroDivisionError: division by zero

  

程序可以通过raise Exceptin来手动抛出异常

>>> raise Exception

Traceback (most recent call last):

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

Exception

>>> raise Exception("hello exception")

Traceback (most recent call last):

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

Exception: hello exception

  

自定义异常类型,只需要继承Exception(或其子类)即可;

>>> raise 1

Traceback (most recent call last):

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

TypeError: exceptions must derive from BaseException

  

不同于C++,只有异常类才能被抛出;

>>> class MyException(Exception):

... pass

...

>>> raise MyException

Traceback (most recent call last):

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

__main__.MyException

  

捕获异常

  

try:

….

except ExceptionType1 as e:

….

except ExceptionType2:

….

raise

except (ExceptionType3, ExceptionType4):

….

except:

else:

  

finally:

  

不带参数的raise用于重新抛出异常;exception (ExceptionType3, ExceptionType4)相比与Java的单参数方式更方便了;

  

不带参数的except捕捉所有类型的异常,但是得不到异常对象,可以使用except BaseException as e 解决(或者Exceptin)

>>> try:

... 1/0

... except BaseException as e:

... print(e)

...

division by zero

  

  

else的块在没有引发异常时执行;finally同java;

  

>>> try:

... 1/0

... except ZeroDivisionError as e:

... print(e)

...

division by zero

  

>>> try:

... 1/0

... finally:

... print('finally')

...

finally

Traceback (most recent call last):

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

ZeroDivisionError: division by zero

  

>>> def f():

... try:

... return 1/0

... finally:

... return 2

...

>>> f()

2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值