Python,异常 exception
来源:互联网 发布:考研什么时候报班 知乎 编辑:程序博客网 时间:2024/05/20 07:51
同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
- python的异常Exception
- python Exception 异常处理
- Python,异常 exception
- Python 异常(Exception)
- python异常 Exception
- Python 异常(Exception)
- Python Exception 异常处理
- Python中的异常(Exception)
- [python相关]try-exception异常处理
- Python中Exception的异常处理
- Python中获取异常(Exception)信息
- Python中获取异常(Exception)信息
- 异常(exception)
- 异常:Exception
- Exception 异常
- 异常Exception
- 异常--Exception
- 异常(exception)
- spring整合Jersey 无法注入service的问题
- introduction to algorithms sorting lesson_3 shell sorting
- 百度图片api
- smail语法 详解
- 在线删除全部数据文件的恢复案例
- Python,异常 exception
- 迁徙至:xingxiudong.com
- ANDROID Porting系列四、建立公开密钥和签名生成
- openfire 修改服务器别名及出现问题
- FIFO、LRU、OPT这三种置换算法的缺页次数
- 深入懂得EventBus的设计思想
- html5小游戏(-)待续
- Xcode中SVN不能提交.a文件的解决方法
- python模拟登陆