利用Python进行数据分析

错误和异常处理

2019-01-02  本文已影响7人  庵下桃花仙

优雅的处理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()
上一篇 下一篇

猜你喜欢

热点阅读