码迷,mamicode.com
首页 > 编程语言 > 详细

Python,异常 exception

时间:2014-09-19 17:37:55      阅读:251      评论:0      收藏:0      [点我收藏+]

标签: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

  

捕获异常

bubuko.com,布布扣

  

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

Python,异常 exception

标签:python   异常   exception   

原文地址:http://blog.csdn.net/icode0410/article/details/39400985

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!