Python包含异常

Pra*_*yot 0 python exception-handling exception

我正在查看python中有一个try: except Exception块的代码.我已经识别出可能引发的代码ValueError.

我的问题:ValueErrorexcept条款中Exception包含(除了已经包含的内容ValueError)之外,是否有意义(或者是一种好的做法)?

try:
    func_raises_value_error()
    func_raises_unknown_error()
except (ValueError, Exception) as e:
  pass
Run Code Online (Sandbox Code Playgroud)

jon*_*rpe 5

捕获特定错误绝对是一种好习惯.有两个一般使用指南try: except::

  1. 保持try块尽可能短; 和
  2. 尽可能具体地说明您要处理哪些错误.

所以而不是像

try:
    print("Please enter your name")
    name = input(" > ")
    print("Please enter your age")
    age = int(input(" > "))
    print("{} is {} years old".format(name, age))
except Exception:
    print("Something went wrong")
Run Code Online (Sandbox Code Playgroud)

你应该有:

print("Please enter your name")
name = input(" > ")
print("Please enter your age")

try:
    age = int(input(" > "))
except ValueError:
    print("That's not a number")
else:
    print("{} is {} years old".format(name, age))
Run Code Online (Sandbox Code Playgroud)

请注意,这允许更具体的错误消息,并允许任何未预料到的错误传递给调用者(根据Python的Zen:"错误不应该默默地传递.除非明确地沉默.")


在您的具体情况下,没有必要使用except (ValueError, Exception) as e:,原因有两个:

  1. Exception已经合并ValueError; 和
  2. 你实际上并没有使用e任何东西.

如果你可以(或想要)对任何一个函数引发的错误做任何事情,你也可以只使用except Exception:(except:至少比裸机更好).