【问题标题】:Python Raising an Exception within "try" block, then catching the same ExceptionPython 在“try”块中引发异常,然后捕获相同的异常
【发布时间】:2021-11-17 18:24:07
【问题描述】:

遇到try/except 块,比如:

def foo(name):
    try:
        if name == "bad_name":
            raise Exception()
    except Exception:
        do_something()
        return

这样做是否有理由,而不是:

def foo(name):
    if name == "bad_name":
        do_something()
        return

【问题讨论】:

  • 在我看来,第一个代码sn -p是对异常处理机制的滥用。
  • 不一定;如果有多个可能引发异常的点,那么所有这些点都可能导致单个 except 块在其中统一处理它们。 (有点像 goto 的严格控制使用。)
  • 这个具体的例子很糟糕。但是,如果在 try:except: 之间还有其他可能引发异常的东西,那么可能。即使在第二种情况下,您也应该避免使用except Exception。如果您知道可能会发生什么样的异常,那么就抓住它们。抓住任何东西都是危险的。

标签: python python-3.x try-except


【解决方案1】:

在您的具体示例中,我也不会使用try/except,因为正如您所说,您可以只使用if 语句。

Try/except 适用于您知道程序可能会崩溃的情况,因此您编写了一些可以运行的代码,而不是整个程序崩溃。例如,您可以使用自定义错误消息覆盖默认错误消息。

一个更好的例子可能是您想将用户写入的数字乘以 2。由于input 函数总是返回string,我们需要使用内置的int 函数将其转换为int。如果用户输入了一个整数,这将正常工作,但如果用户输入的是str,整个程序就会崩溃。假设如果发生这种情况,我们想打印一条消息,我们可以使用try/except。如果我们还想一遍又一遍地重复这个问题,直到用户输入一个整数,我们可以使用一个简单的while 循环。下面的代码就是这个的实现。

print("Write any integer and I will multiply it with two!")

while True:
    # Get user input
    userInput = input("Write any number: ")
    try:
        # Here we try to cast str to int
        num = int(userInput)

        # The next line will only be run if the line before 
        # didn't crash. We break out of the while loop
        break

    # If the casting didn't work, this code will run
    # Notice that we store the exception as e,
    # so if we want we could print it
    except Exception as e:
        print("{} is not an integer!\n".format(userInput))

# This code will be run if the while loop
# is broken out of, which will only happen
# if the user wrote an integer
print("Your number multiplied with 2:\n{}".format(num * 2))

预期结果:

Write any integer and I will multiply it with two!
Write any number: a
a is not an integer!

Write any number: b
b is not an integer!

Write any number: 4
Your number multiplied with 2:
8

【讨论】:

    猜你喜欢
    • 2014-07-09
    • 2012-09-04
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 2012-05-02
    • 2022-01-27
    相关资源
    最近更新 更多