blakev
blakev

Reputation: 4449

What's the proper way to reraise a custom exception?

If I have the function,

def parse_datetime(s, **kwargs):
    """ Converts a time-string into a valid
    :py:class:`~datetime.datetime.DateTime` object.

        Args:
            s (str): string to be formatted.

        ``**kwargs`` is passed directly to :func:`.dateutil_parser`.

        Returns:
            :py:class:`~datetime.datetime.DateTime`
    """
    if not s:
        return None
    try:
        ret = dateutil_parser(s, **kwargs)
    except (OverflowError, TypeError, ValueError) as e:
        logger.exception(e, exc_info=True)
        raise SyncthingError(*e.args)
    return ret

What's the most correct way to raise the caught exception as the common library exception? (SyncthingError(Exception) ) The way it's written right now does not work correctly.

Upvotes: 2

Views: 258

Answers (2)

VPfB
VPfB

Reputation: 17247

In Python 3 the exceptions can be chained,

raise SyncthingError("parsing error") from e

will produce a stack trace with details of the original exception.

There are examples in the raise statement docs.

Upvotes: 3

smishra
smishra

Reputation: 3418

You should be able to raise it as long as constructer of the common library exception takes Error or Exception. For example:

Class LibraryException(Exception)...
Class LibraryException(Error)...

Upvotes: 0

Related Questions