【问题标题】:Where does the try/except statement go when calling a function?调用函数时,try/except 语句在哪里?
【发布时间】:2020-08-21 15:46:25
【问题描述】:

我有我要调用函数的主要 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

【问题讨论】:

  • 第二个版本不会有太大用处,除非你让 error 变量可以被调用上下文以某种方式访问​​。
  • 我不会捕捉到函数中的错误。如果你这样做了,你的函数就会担心处理错误以及它的实际任务。如果它抛出,它就会抛出。任何想处理错误的人都可以抓住它。有时它是合适的,但我看不出这里有任何理由为什么该函数应该知道关于 error 的任何信息。
  • 可能是 both 的组合,具体取决于 可能 引发的异常。其中一些你可以在函数内部以某种方式处理,其他的可能更好地传播给其他人一个处理它们的机会。

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


【解决方案1】:

第一种方法可行

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

【讨论】:

    【解决方案2】:

    由于函数调用是从 try 块内部进行的,因此函数代码执行过程中的任何错误/异常也会出现在 try 块的区域内,因此将被重定向到 except 块。

    一个简单的例子如下:

    def test():
        raise Exception 
    
    try:
        test()
    
    except:
        error = True
        print(error)
    

    输出将是:

    是的

    【讨论】:

      猜你喜欢
      • 2022-01-22
      • 2011-09-29
      • 1970-01-01
      • 1970-01-01
      • 2013-04-10
      • 1970-01-01
      • 2018-02-24
      • 1970-01-01
      • 2014-09-04
      相关资源
      最近更新 更多