Yuan的学习笔记
作者 Yuan
我们写程序时常常会遇到各种错误,比如下面一个例子,当把一个字符串转化为浮点数类型时,程序就会报错:
In [1]: float('1.2345')
Out[1]: 1.2345
In [2]: float('something')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-2-2649e4ade0e6> in <module>
----> 1 float('something')
ValueError: could not convert string to float: 'something'
最下面的ValueError告诉你,不能把字符串转化为浮点数。当有用户使用我们编写的程序时可能因为某些原因(比如不小心或不会用)导致了程序出错,我们可能需要更优雅的处理这些错误。比如我们可以写一个函数:
def attempt_float(x):
try:
return float(x)
except:
print('could not convert string to float')
return x
当float(x)出异常的时候,会执行下面except的部分:
In [4]: attempt_float('1.2345')
Out[4]: 1.2345
In [5]: attempt_float('something')
could not convert string to float
Out[5]: 'something'
若我们输入了一个元组进去:
In [6]: float((1, 2))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-6-82f777b0e564> in <module>
----> 1 float((1, 2))
TypeError: float() argument must be a string or a number, not 'tuple'
我们可以看到这次抛出的异常不是ValueError而是TypeError(类型错误),我们可以只处理ValueError的错误:
def attempt_float(x):
try:
return float(x)
except ValueError:
print('could not convert string to float')
return x
当要把’banana’转化为浮点数时(ValueError):
In [9]: attempt_float('banana')
could not convert string to float
Out[9]: 'banana'
当要把元组转化为浮点数时(TypeError):
In [10]: attempt_float((1,2))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-10-102527222085> in <module>
----> 1 attempt_float((1,2))
<ipython-input-8-3ff52c4ecd95> in attempt_float(x)
1 def attempt_float(x):
2 try:
----> 3 return float(x)
4 except ValueError:
5 print('could not convert string to float')
TypeError: float() argument must be a string or a number, not 'tuple'
我们也可以用元组包含多个异常:
def attempt_float(x):
try:
return float(x)
except (ValueError, TypeError):
return x
如果对你有帮助的话,就点个赞吧。下一篇笔记是文件和操作系统。
—完—
Yuan的学习笔记
作者 Yuan