Search code examples
pythonpython-3.xerror-handlingtry-except

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


I have my main Python script where I am calling a function. I want to catch any errors that happen during the execution of the function and if there are any errors I want to set the error variable to true. Is the try/except statement done in the main script like so:

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

except:
  error = true

Or is it done inside the function like this:

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

Solution

  • The first method will work

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