调用函数时 try/except 语句去哪里了?

Where does the try/except statement go when calling a function?

我有我的主要 Python 脚本,我在其中调用一个函数。我想捕获函数执行期间发生的任何错误,如果有任何错误我想将错误变量设置为 true。 try/except 语句在主脚本中是否像这样完成:

try:
  image_convert(filepath,'.jpg','RGB',2500,2500)

except:
  error = true

或者像这样在函数内部完成:

def image_convert(filepath,imageType,colorMode,height,width):
   try:
    imwrite(filepath[:-4] + imageType, imread(filepath)[:,:,:3].copy()) # <-- using the imagecodecs library function of imread, make a copy in memory of the TIFF File.
    # The :3 on the end of the numpy array is stripping the alpha channel from the TIFF file if it has one so it can be easily converted to a JPEG file.
    # Once the copy is made the imwrite function is creating a JPEG file from the TIFF file.
    # The [:-4] is stripping off the .tif extension from the file and the + '.jpg' is adding the .jpg extension to the newly created JPEG file.
    img = Image.open(filepath[:-4] + imageType) # <-- Using the Image.open function from the Pillow library, we are getting the newly created JPEG file and opening it.
    img = img.convert(colorMode) # <-- Using the convert function we are making sure to convert the JPEG file to RGB color mode.
    imageResize = img.resize((height, width)) # <-- Using the resize function we are resizing the JPEG to 2500 x 2500
    imageResize.save(filepath[:-4] + imageType) # <-- Using the save function, we are saving the newly sized JPEG file over the original JPEG file initially created.
    return(imageResize)
  except:
     error = true

第一种方法可行

try:
    image_convert(filepath,'.jpg','RGB',2500,2500)
except:
    error = true

由于函数调用是从 try 块内部进行的,因此函数代码执行期间的任何 errors/exceptions 也会进入 try 块的区域,因此将被重定向到 except 块。

一个简单的例子如下:

def test():
    raise Exception 

try:
    test()

except:
    error = True
    print(error)

输出将是:

正确