python处理输入错误_在python错误处理中输入类型

如果each_line没有足够的逗号,或者任何一个值不是数字(例如,空字符串),则有几个地方可能会失败。在每种情况下,您都可以捕获错误并使用continue跳到f中的下一个项目:

for each_line in f:

try:

foo_line, bar_line = each_line.split(',')

except ValueError:

# "Too many/few values to unpack" meaning wrong number of commas!

continue

try:

foo, bar = int(foo_line), int(bar_line)

except ValueError:

# "invalid literal for int()" meaning it wasn't digits

continue

foobar = FooBar(foo,bar)

foobar_list.append(foobar)我已将其分解为两个独立的异常处理程序,因为它有两种不同的失败方式。你实际上可以折叠起来像:

for each_line in f:

try:

foo_line, bar_line = each_line.split(',')

foo, bar = int(foo_line), int(bar_line)

except ValueError:

# there was invalid input.

continue

foobar = FooBar(foo,bar)

foobar_list.append(foobar)因为它是相同的例外,它们紧密相连。就个人而言,我更喜欢前者,因为它确实存在两种错误。你不应该做的是:

# !!! BAD !!!

for each_line in f:

try:

each_line = each_line.split(',')

foo = int(each_line[0])

bar = int(each_line[1]

foobar = FooBar(foo,bar)

foobar_list.append(foobar)

except ValueError:

continue因为FooBar()甚至foobar_list.append()可能会失败,但异常处理程序可以吞下它;始终使yoru异常处理程序中的try:套件尽可能小,以便它们只捕获一个错误,并且容易找到错误。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值