处理Python的错误或异常是构建稳定程序的重要组成部分。在数据分析应用中,很多函数只能处理特定的输入。例如,Python的float
函数可以将字符串转换为浮点数字,但是对不正确的输入会产生ValueError
:
float('0.1') # 结果:0.1
float('hello') # 结果:ValueError: could not convert string to float: 'hello'
假设我们想要在float函数运行失败时可以优雅地返回输入参数,我们可以通过将float
函数写入一个try/except
代码段来实现:
def f(s):
try:
return float(s)
except ValueError:
return s
f('0.1') # 结果:0.1
f('hello') # 结果:hello
上述代码的意思就是:当float(s)
没有错误的时候,会返回float(s)
,但当出现ValueError
的时候,就会返回s
本身。
不过上述代码只能处理ValueError
的情况,当出现其它报错情况时,同样会报错:
f((1, 2)) # 结果:TypeError: float() argument must be a string or a number, not 'tuple'
这是因为错误类型是TypeError
,但我们只设置了ValueError
时的处理方式,可使用下面两种方式:
def f(s):
try:
return float(s)
except:
return s
f((1, 2)) # 结果:(1, 2)
或者
def f(s):
try:
return float(s)
except (ValueError, TypeError): # 括号必不可少
return s
f((1, 2)) # 结果:(1, 2)
某些情况下,我们可能想要处理一个异常,但是希望一部分代码无论try代码块是否报错都要执行。为了实现这个目的,使用finally
关键字,一般用于读写文件:
try:
f = open("/tmp/output", "w")
f.write("hello")
finally:
print("closing file")
f.close()
不论try
中写文件的过程中是否有异常,finally
中关闭文件的操作一定会执行。由于finally
的这个特性,finally
经常被用来做一些清理工作。