首页 > 解决方案 > 如何修复不起作用的 Python Try/Except 语句

问题描述

我正在尝试在我的 Python 程序中合并一些错误处理,以便每当我的图像转换代码块抛出一个不会停止程序但会继续运行的错误时,但每次我遇到错误时它都会停止程序。我究竟做错了什么?这是我的代码:

if file.lower().endswith('.tif'): # <-- If file is a TIFF file and there are no errors yet
    try:
        imwrite(filepath[:-4] + '.jpg', 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] + '.jpg') # <-- Using the Image.open function from the Pillow library, we are getting the newly created JPEG file and opening it.
        img = img.convert('RGB') # <-- Using the convert function we are making sure to convert the JPEG file to RGB color mode.
        imageResize = img.resize((2500, 2500)) # <-- Using the resize function we are resizing the JPEG to 2500 x 2500
        imageResize.save(filepath[:-4] + '.jpg') # <-- Using the save function, we are saving the newly sized JPEG file over the original JPEG file initially created.
    except ValueError:
        print('There was an error with the Image')

标签: pythonpython-3.xerror-handlingtry-except

解决方案


而不是except ValueError你应该做except Exception因为可能的问题是抛出的错误不是值错误,所以现在如果发生任何错误,它将进入 except 部分

   try:
       do something
   except Exception:
       do something else

    

推荐阅读