如果没有发生错误则引发异常

Raising exception if error does not occur

我在 python3 中使用 selenium webdriver。当驱动程序到达某个页面并且如果存在带有 class shiftUp 的某个 class 元素时,我想打印响应并在该点停止执行。目前,我是这样做的:

flag = 0
try:
    error_source_file = driver.find_element_by_class_name("shiftUp")
    flag = 1
except:
    pass
if flag:
    print("RESPONSE")
    sys.exit()

我想要一个正确的方法。

使用 else 子句:

try:
    error_source_file = driver.find_element_by_class_name("shiftUp")
except NoSuchElementException:
    pass
else:
    print("RESPONSE")
    sys.exit()

它会在不引发错误的情况下触发:https://docs.python.org/3/tutorial/errors.html#handling-exceptions:

The try … except statement has an optional else clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception.

The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try … except statement.

出于类似的原因,我建议只捕获 NoSuchElementException:您不想捕获您不想捕获的错误。

为什么不呢:

try:
    error_source_file = driver.find_element_by_class_name("shiftUp")
    print("RESPONSE")
    sys.exit()
except NoSuchElementException:
    pass

如果 find_element 方法引发异常,则不会执行 error_source_file 之后的行。

NB: Consider precising the type of the exception you want to catch (ex: except IndexError:), or you could silent errors, which is really bad.