什么时候可以捕获错误(在函数中)?

When can the error be caught (in functions)?

如果方法 A 调用 B,B 调用 C,然后在函数 C 中引发错误,它可能在哪里被捕获(A、B、C 或以上所有)?

你可以写个简短的代码,自己试试看。像这样:

def func1(a):  #will call func2
    print("in first func #1")
    x=a^2
    func2(x)
    print("in first func #2")
def func2(b):  #will call func3
    print("in second func #1")
    func3(b*2)
    print("in second func #2")
def func3(c):  #function with error
    print("in third func #1")
    print(c+ "str")  #can't use + operator on str and int type
    print("in third func #2")
a=5
func1(a)

你最终会遇到这个错误:

in first func #1
in second func #1
in third func #1
Traceback (most recent call last):
  File "--", line 15, in <module>
    func1(a)
  File "--", line 4, in func1
    func2(x)
  File "--", line 8, in func2
    func3(b*2)
  File "--", line 12, in func3
    print(c+ "str")  #can't use + operator on str and int type
TypeError: unsupported operand type(s) for +: 'int' and 'str'

可以在func3

中捕获