2

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.

blakev
  • 4,154
  • 2
  • 32
  • 52
  • If you want to raise `SyncthingError` then just do: `raise SyncthingError(e)`. If you want to raise the exception you caught, just do `raise` – Alastair McCormack Mar 06 '18 at 17:14
  • 1
    Can you try [`raise ... from ...`](https://www.python.org/dev/peps/pep-3134/#explicit-exception-chaining)? – Cong Ma Mar 06 '18 at 17:16

2 Answers2

3

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.

VPfB
  • 14,927
  • 6
  • 41
  • 75
  • Is there a Python2 fallback? This is very elegant. – blakev Mar 06 '18 at 17:20
  • 1
    @blakev there's a compatibility-layer implementation from [`six`](http://pythonhosted.org/six/#six.raise_from) In Python 2 this doesn't do much, but it prevents `SyntaxError`. There's also the `reraise()` function worth looking into. – Cong Ma Mar 06 '18 at 17:22
  • @blakev I have started learning Python from version 3. I had to search and found this: https://stackoverflow.com/questions/1350671/inner-exception-with-traceback-in-python Very similar to your question. – VPfB Mar 06 '18 at 17:24
0

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)...
smishra
  • 3,122
  • 29
  • 31