File: exception.py

package info (click to toggle)
sasmodels 1.0.1-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 15,888 kB
  • sloc: python: 25,392; ansic: 7,377; makefile: 149; sh: 61
file content (51 lines) | stat: -rw-r--r-- 1,457 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
"""
Utility to add annotations to python exceptions.
"""
import sys

# Platform cruft: WindowsError is only defined on Windows.
try:
    WindowsError
except NameError:
    class WindowsError(Exception):
        """
        Fake WindowsException when not on Windows.
        """
        pass

def annotate_exception(msg, exc=None):
    """
    Add an annotation to the current exception, which can then be forwarded
    to the caller using a bare "raise" statement to raise the annotated
    exception.  If the exception *exc* is provided, then that exception is the
    one that is annotated, otherwise *sys.exc_info* is used.

    Example::

        >>> D = {}
        >>> try:
        ...    print(D['hello'])
        ... except:
        ...    annotate_exception("while accessing 'D'")
        ...    raise
        Traceback (most recent call last):
            ...
        KeyError: "hello while accessing 'D'"
    """
    if not exc:
        exc = sys.exc_info()[1]

    # Can't extend WindowsError exceptions; instead raise a new exception.
    # TODO: try to incorporate current stack trace in the raised exception
    if isinstance(exc, WindowsError):
        raise OSError(str(exc) + " " + msg)

    args = exc.args
    if not args:
        exc.args = (msg,)
    else:
        try:
            arg0 = " ".join((args[0], msg))
            exc.args = tuple([arg0] + list(args[1:]))
        except:
            exc.args = (" ".join((str(exc), msg)),)