【问题标题】:How to I make exception in exception when catching errors in python?在python中捕获错误时如何在异常中产生异常?
【发布时间】:2020-06-15 21:53:58
【问题描述】:

所以,我有这段代码,工作得很好,但我想有可能,如果我输入 x,它会让我回到我有的选择列表的开头

def ask2():
while True:
    try:
        number = int(input('Pick a number in range 1-100: '))
    except ValueError:  # just catch the exceptions you know!
        print('That\'s not a number!')
    else:
        if 1 <= number <= 100:  # this is faster
            print("added")
        else:
            print('Out of range. Try again')

【问题讨论】:

  • 然后当我最后添加时,它说局部变量号可能在分配之前被引用
  • 初始化变量之前
  • 我只想把“继续”放在你打印“添加”的地方,以打破 while True。但是,由于它在函数内部,因此您可以使用“return”。

标签: python function if-statement exception error-handling


【解决方案1】:

Guido van Rossum 花了一些时间使用 Java,这确实 支持组合 except 块和 finally 块的等价物, 这澄清了声明的含义:

try:
    block-1 ...
except Exception1:
    handler-1 ...
except Exception2:
    handler-2 ...
else:
    else-block
finally:
    final-block

block-1 中的代码被执行。如果代码引发exception,则 测试各种 except 块:如果异常属于类 Exception1, handler-1 被执行;否则,如果它是类的 Exception2、handler-2 被执行,等等。如果没有例外 引发,else-block 被执行。

无论之前发生了什么,final-block 都会执行一次 代码块已完成,任何引发的异常都已处理。即使 异常处理程序或 else-block 中存在错误和新的 引发异常,final-block 中的代码仍在运行。


PEP 341: Unifying try-except and try-finally

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-01
    • 2015-09-21
    • 1970-01-01
    • 2011-12-26
    • 1970-01-01
    • 2015-06-11
    • 2018-10-22
    • 1970-01-01
    相关资源
    最近更新 更多