Python数据分析笔记#4 错误和异常处理

错误和异常处理

我们写程序时常常会遇到各种错误,比如下面一个例子,当把一个字符串转化为浮点数类型时,程序就会报错:

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
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值