【问题标题】:Handling COMError in Python?在 Python 中处理 COMError?
【发布时间】:2018-10-19 05:37:03
【问题描述】:

运行我的脚本,我收到一些文件的以下错误:

COMError: (-2146822496, None, ('The file appears to be corrupted.', 
'Microsoft Word', 'wdmain11.chm', 25272, None))

我已经导入了comtypes,我希望在出现这个错误时做一个异常,所以我做了以下操作:

try:
    code...
except comtypes.COMError:
    pass

但似乎 Python 无法识别该异常,因为它会产生与以前相同的 COMError。

关于如何解决这个问题的任何建议?谢谢。

【问题讨论】:

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


    【解决方案1】:

    您可能需要显示更多代码才能让任何人帮助您。我遇到了类似的问题,但我的应用程序有点不同。我会尽力协助的。

    您需要实际处理发生的错误。 所以当你得到异常时,你需要做这样的事情:

    假设这是你的错误:

    COMError: (-2146822496, None, ('文件似乎已损坏。', 'Microsoft Word', 'wdmain11.chm', 25272, None))

    except comtypes.COMError as ce:
    # get the error information
    target_error = ce.args # error in a tuple form
    # target_error[0] -> -2146822496
    # target_error[1] -> None
    # target_error[2] -> 'The file appears to be corrupted.',  'Microsoft Word', 'wdmain11.chm', 25272, None
    # target_error[2] is another tuple made up of
    # [2][0] -> 'The file appears to be corrupted.'
    # [2][1] -> 'Microsoft Word'
    # [2][2] -> 'wdmain11.chm'
    # [2][3] -> 25272
    # [2][4] -> None
    
    if target_error[2][0] == 'The file appears to be corrupted.':
        print("# handle your error here inside this if statement")
    

    关键是一旦你得到实际的错误,你就可以采取相应的措施来处理它。 同样,如果没有看到您的代码,很难提供更多建议,但您可以根据应用程序类型(“Microsoft Word”)或错误代码(“文件似乎已损坏。”)来处理错误。

    【讨论】:

      猜你喜欢
      • 2016-09-06
      • 2016-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多