python - 在python中捕获错误时如何使异常发生异常?

标签 python function if-statement exception error-handling

所以,我有这段代码,工作得很好,但是我想输入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')

最佳答案

Guido van Rossum spent some time working with Java, which does support the equivalent of combining except blocks and a finally block, and this clarified what the statement should mean:


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

The code in block-1 is executed. If the code raises an exception, the various except blocks are tested: if the exception is of class Exception1, handler-1 is executed; otherwise if it's of class Exception2, handler-2 is executed, and so forth. If no exception is raised, the else-block is executed.

No matter what happened previously, the final-block is executed once the code block is complete and any raised exceptions handled. Even if there's an error in an exception handler or the else-block and a new exception is raised, the code in the final-block is still run.



PEP 341: Unifying try-except and try-finally

关于python - 在python中捕获错误时如何使异常发生异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60508555/

相关文章:

r - 如何从函数内打印空行?

c++ - 如何将数据传递给多个函数

python - 如何使函数从 Python 中的函数外部获取变量?

php - 分页以显示最大值并限制其余值

python - 用另一个数组替换部分数组的最佳方法

python - 是否可以使用 GitLab CI 将文件写入您的计算机(本地驱动器)?

python - if 语句中无法识别来自 xml.etree.cElementTree 的类型元素

javascript - 没有 if 语句限制数字

python - 外部循环第一次迭代后嵌套 for 循环未运行

python - 如何等到 Excel 计算公式后再继续使用 win32com