优雅的处理Pyhton错误或异常。
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'
In [3]: def attempt_float(x):
...: try:
...: return float(x)
...: except:
...: return x
...:
In [4]: attempt_float('2.22')
Out[4]: 2.22
In [5]: attempt_float('something')
Out[5]: 'something'
捕获一个异常。
In [6]: def attempt_float(x):
...: try:
...: return float(x)
...: except ValueError:
...: return x
...:
捕获多个异常。
In [7]: def attempt_float(x):
...: try:
...: return float(x)
...: except (TypeError, ValueError):
...: return x
使用 finally 关键字,不管 try 代码块是否出错都执行。
In [8]: f = open(path, 'w')
In [9]: try:
...: write_to_file(f)
...: finally:
...: f.close()
用 else 执行当 try 代码块执行成功后才会执行的代码。
In [10]: f = open(path, 'w')
In [11]: try:
...: write_to_file(f)
...: except:
...: print('Failed')
...: else:
...: print('Succeeded')
...: finally:
...: f.close()
网友评论