Pythonic ways to catch exceptions based on their properties

79 views Asked by At

pywintypes exposes a com_error like this:

from dataclasses import dataclass
from typing import Optional


@dataclass
class com_error(Exception):
    hresult: int  # The COM hresult
    strerror: str  # The error message
    excepinfo: Optional[tuple]  # An optional EXCEPINFO tuple.
    argerror: Optional[int]  # The index of the argument in error, or (usually) None or -1

# example usage
raise com_error(
    -2147352567,
    "Exception occurred.",
    (0, "Microsoft Excel", "Cannot access 'outAddin.xlam'.", "xlmain11.chm", 0, -2146827284),
    None,
)

The important error number is -2146827284 or err.hresult, this defines the type of com error.

Is there a pythonic way to catch a com_error where the hresult property has a particular value? Maybe by defining a custom error subclass of com_error with a specific hresult - perhaps there is an equality operator I can overload?

1

There are 1 answers

2
Prahken On

I'd go for something standard, unless you're the one actively raising the exceptions and you want to have a specific class for your error code of interest.

try:
    # example usage
    raise com_error(
        -2147352567,
        "Exception occurred.",
        (0, "Microsoft Excel", "Cannot access 'outAddin.xlam'.", "xlmain11.chm", 0, -2146827284),
    None,
    )
except com_error as e:
    if e.hresult==-2146827284:
        # Handle this however you want
        pass
    else:
        raise e # Assuming you only want to catch the com_error with your code