Python except 关键字

Python except 关键字

0、定义和用法

try ... except 块中使用了关键字 except。它定义 try 块引发错误时要运行的代码块。

您可以为不同的错误类型定义不同的块,以及没有问题的情况下执行的块,请参见下面的例子。

1、更多实例

实例一

如果引发 NameError 则写一条消息,如果引发 TypeError 则写另一条:

x = "hello"

try:
  x > 3
except NameError:
  print("You have a variable that is not defined.")
except TypeError:
  print("You are comparing values of different type")

# 结果: You are comparing values of different type

实例二

尝试执行一条引发错误的语句,但没有定义的错误类型(在这种情况下为 ZeroDivisionError):

try:
  x = 1/0
except NameError:
  print("You have a variable that is not defined.")
except TypeError:
  print("You are comparing values of different type")
except:
  print("Something else went wrong")

# 结果: Something else went wrong

实例三

如果没有出现错误,写一条消息:

x = 1

try:
  x > 10
except NameError:
  print("You have a variable that is not defined.")
except TypeError:
  print("You are comparing values of different type")
else:
  print("The 'Try' code was executed without raising any errors!")

# 结果:The 'Try' code was executed without raising any errors!
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值