在Python中引发异常时了解范围

Understanding scopes when raising exceptions in Python

1
2
3
4
5
6
7
8
9
def set_attribute(attributes, name, value):
    for i, attribute in enumerate(attributes):
        if name in attribute:
            quote_char = attribute.find('"')
            if quote_char == -1:
                raise ValueError
                return None
            attributes[i] = attribute[:quote_char+1] + str(value) + '"'
            return attributes

我是一个新的程序员,我正在努力正确理解异常处理。

在这个例子中,每个name在某个地方都应该有一个"字符,所以如果失败了,我想提出一个例外,但我也试图理解return None语句是否必要(或做任何事情)。

我的理解是,在找到异常处理程序之前,我将从每个级别的作用域中逃脱。python教程说:

  • First, the try clause (the statement(s) between the try and except keywords) is executed.
  • If no exception occurs, the except clause is skipped and execution of the try statement is finished.
  • If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception named
    after the except keyword, the except clause is executed, and then
    execution continues after the try statement.
  • If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception named
    after the except keyword, the except clause is executed, and then
    execution continues after the try statement.
  • If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no
    handler is found, it is an unhandled exception and execution stops
    with a message as shown above.

然而,在阅读了这个描述之后,我意识到我不理解异常,但我应该理解。

因此,简单地说一句:这是必要的,为什么?另外,关于异常如何工作,我哪里错了呢?


return None是垃圾。Python永远不会到达那里。

您可以简化代码并运行一个小实验,看看是否返回值FOO

1
2
3
4
5
6
7
8
9
10
11
def foo():
    if True:
        raise ValueError('Bad value')
        return 'FOO'
    return 'BAR'

try:
    print(foo())
except ValueError as err:
    print(err)
    # Bad value

如果返回FOO,您可能会在print(foo())中看到它,但实际上该行不打印任何内容。相反,你看到的是Bad value