Python之异常

常见错误:

>>> print 'hello' #试图使用Python2的语法产生SyntaxError
  File "<stdin>", line 1
    print 'hello'
                ^
SyntaxError: Missing parentheses in call to 'print'
>>>  print('hello') #首行多打了一个空格产生IndentationError
  File "<stdin>", line 1
    print('hello')
    ^
IndentationError: unexpected indent
>>> print(undefined) #试图访问未定意思的变量产生NameError
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'undefined' is not defined
>>> print(1 + 'wow')#操作或函数应用于不适当的对象产生TypeError
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> 

处理异常:

>>> def get_number():
...     "Returns a float number"
...     number = float(input("Enter a float number: "))
...     return number
...
>>>
>>> while True:
...     try:
...         print(get_number())
...     except ValueError:
...         print("You entered a wrong value.")
...
Enter a float number: 45.0
45.0
Enter a float number: 24,0
You entered a wrong value.
Enter a float number: Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
  File "<stdin>", line 3, in get_number
KeyboardInterrupt

首先输入了一个合适的浮点值,解释器返回输出这个值。

然后输入以逗号分隔的值,抛出 ValueError 异常,except 子句捕获,并且打印出错误信息。

第三次按下 Ctrl + C ,导致了 KeyboardInterrupt 异常发生,这个异常并未在 except 块中捕获,因此程序执行被中止。

一个空的 except 语句能捕获任何异常。

>>> try:
...     input() # 输入的时候按下 Ctrl + C 产生 KeyboardInterrupt
... except:
...     print("Unknown Exception")
...
Unknown Exception

抛出异常:

>>> try:
...     raise ValueError("A value error happened.")#抛出异常
... except ValueError: #可以像捕获其他异常一样捕获抛出的异常
...     print("ValueError in our code.")
...
ValueError in our code.

定义清理行为:

try 语句还有另一个可选的 finally 子句,目的在于定义在任何情况下都一定要执行的功能。例如:

>>> try:
...     raise KeyboardInterrupt
... finally:
...     print('Goodbye, world!')
...
Goodbye, world!
KeyboardInterrupt
Traceback (most recent call last):
  File "<stdin>", line 2, in ?

不管有没有发生异常,finally 子句 在程序离开 try 后都一定会被执行。当 try 语句中发生了未被 except 捕获的异常(或者它发生在 exceptelse 子句中),在 finally 子句执行完后它会被重新抛出。

在真实场景的应用程序中,finally 子句用于释放外部资源(文件或网络连接之类的),无论它们的使用过程中是否出错。

以上内容均摘抄自实验楼:https://www.shiyanlou.com/courses/596/labs/2045/document

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值