调用函数时,try / except语句在哪里?

问题描述

我有我要调用函数的主要Python脚本。我想捕获函数执行期间发生的任何错误,如果有任何错误,我想将error变量设置为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块内部进行函数调用,因此在执行功能代码期间发生的任何错误/异常也将进入try块的区域内,因此将被重定向到except块。

一个简单的例子如下:

def test():
    raise Exception 

try:
    test()

except:
    error = True
    print(error)

输出将是: