python3 错误处理

try

try .... except ... else

try:
   your operations
   ......................
except ExceptionI:
   If there is ExceptionI, then execute this block.
except ExceptionII:
   If there is ExceptionII, then execute this block.
   ......................
else:
   If there is no exception then execute this block.
  • 一个try语句可以有多个except语句。 当try块包含可能引发不同类型的异常的语句时,这就很有用。
  • 还可以提供一个通用的except子句,它处理任何异常。
  • 在except子句之后,可以包含一个else子句。 如果try:block中的代码不引发异常,则else块中的代码将执行。
  • else-block是一个不需要try:block保护的代码的地方。

except子句没有指定异常

也可以使用except语句,但不定义异常:

try:
   your operations here
   ......................
except:
   If there is any exception, then execute this block.
   ......................
else:
   If there is no exception then execute this block.

这种try-except语句捕获所有发生的异常。使用这种try-except语句不被认为是一个很好的编程实践,因为它捕获所有异常,但不会让程序员能更好地识别发生的问题的根本原因。

except子句指定多个异常

还可以使用相同的except语句来处理多个异常,如下所示:

try:
   your operations
   ......................
except(Exception1[, Exception2[,...ExceptionN]]]):
   If there is any exception from the given exception list, 
   then execute this block.
   ......................
else:
   If there is no exception then execute this block.

try-finally子句

可以使用finally:块和try:块。 finally:块是放置必须执行代码的地方,无论try块是否引发异常。

try:
   your operations
   ......................
   Due to any exception, this may be skipped.
finally:
   This would always be executed.

可以提供except子句或finally子句,但不能同时提供。不能使用else子句以及finally子句。

抛出异常

可以通过使用raise语句以多种方式引发异常。

raise [Exception [, args [, traceback]]]

Exception是异常的类型(例如,NameError),args是异常参数的值。 参数是可选的; 如果没有提供,则异常参数为None。
最后一个参数traceback也是可选的(在实践中很少使用),如果存在,则是用于异常的追溯对象。

def functionName( level ):
   if level <1:
      raise Exception(level)
   return level

try:
   l = functionName(-10)
   print ("level = ",l)
except Exception as e:
   print ("error in level argument",e.args[0])

输出:

error in level argument -10

 

转载于:https://www.cnblogs.com/xiaojianliu/articles/10028902.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值