函数前和函数中<try>和<except>的区别

difference between <try> and <except> before the function & in the function

当我在函数前使用 try 时,它会引发错误。但是如果我使用它 in 函数就可以了。为什么?(这些代码的评估顺序是什么?)。感谢任何帮助。

try:
    def chiz(dict, key):
        return dict[key]
except:
    print("somethig went wrong")
user_01 = {
    "name": "armin",
    "age": 20.51
}
chiz(user_01, "weight")

>>>Traceback (most recent call last):
  File "C:\Users\user\PycharmProjects\pythonWhile\test.py", line 11, in <module>
    chiz(user_01, "weight")
  File "C:\Users\user\PycharmProjects\pythonWhile\test.py", line 3, in chiz
    return dict[key]
KeyError: 'weight'


def chiz(dict, key):
    try:
        return dict[key]

    except :
        print("somethig went wrong")

user_01 = {
    "name": "armin",
    "age": 20.51
}

chiz(user_01, "weight")

第一个示例中的 try 不会在函数被调用时被求值,只有当函数被首次定义时才会被求值,此时不会引发异常。

直到您实际使用给定字典中不存在键的参数调用函数时,才会实际引发异常,然后才不会评估 try/except 子句。

你的第二个例子是做你想做的事情的正确方法:

In [4]: def chiz(dict, key): 
   ...:     try: 
   ...:         return dict[key] 
   ...:     except: 
   ...:         print("Something went wrong") 
   ...:                                                                         

In [5]: chiz(user_01, "weight")                                                 
Something went wrong

话虽这么说,请重新考虑那个简单的 except 子句。相当于说except BaseException:,这可能不是你想要的,是反对PEP8 recommendations的。在这种情况下,您可能应该使用 except KeyError: 或最广泛的 except Exception:.

When catching exceptions, mention specific exceptions whenever possible instead of using a bare except: clause. A bare except: clause will catch SystemExit and KeyboardInterrupt exceptions, making it harder to interrupt a program with Control-C, and can disguise other problems. If you want to catch all exceptions that signal program errors, use except Exception: (bare except is equivalent to except BaseException:). A good rule of thumb is to limit use of bare 'except' clauses to two cases:

  • If the exception handler will be printing out or logging the traceback; at least the user will be aware that an error has occurred.
  • If the code needs to do some cleanup work, but then lets the exception propagate upwards with raise. try...finally can be a better way to handle this case.

来自 PEP463

any situation where you catch an exception you don't expect to catch is an unnecessary bug magnet.