【问题标题】:How do I fix a Python Try/Except statement that is not working [closed]如何修复不起作用的 Python Try/Except 语句 [关闭]
【发布时间】:2020-11-20 13:36:13
【问题描述】:

我正在尝试在我的 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')

【问题讨论】:

  • 你遇到了什么错误?
  • 您可能没有处理正确的错误。请堆栈跟踪。 edit你的帖子。
  • 我收到异常已发生:ValueError 消息
  • 我也尝试了 except: continue ,但它仍然会因错误而停止程序
  • 为什么第一行使用file,其余使用filepath

标签: python python-3.x error-handling try-except


【解决方案1】:

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

   try:
       do something
   except Exception:
       do something else

    

【讨论】:

  • 我试过了,还是报错
  • 那么 100% 错误不在这行代码中,它可能在 If 语句或任何其他代码块中
猜你喜欢
  • 1970-01-01
  • 2016-09-23
  • 1970-01-01
  • 1970-01-01
  • 2013-04-10
  • 2017-11-30
  • 2011-09-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多