source: sasmodels/sasmodels/exception.py @ d1fe925

gh-pages
Last change on this file since d1fe925 was d1fe925, checked in by ajj, 8 years ago

Creating gh_pages branch for docs

  • Property mode set to 100644
File size: 1.2 KB
Line 
1"""
2Utility to add annotations to python exceptions.
3"""
4
5# Platform cruft: WindowsError is only defined on Windows.
6try:
7    WindowsError
8except NameError:
9    class WindowsError(Exception):
10        pass
11
12def annotate_exception(exc, msg):
13    """
14    Add an annotation to the current exception, which can then be forwarded
15    to the caller using a bare "raise" statement to reraise the annotated
16    exception.
17    Example::
18        >>> D = {}
19        >>> try:
20        ...    print D['hello']
21        ... except Exception,exc:
22        ...    annotate_exception(exc, "while accessing 'D'")
23        ...    raise
24        Traceback (most recent call last):
25            ...
26        KeyError: "hello while accessing 'D'"
27    """
28    # Can't extend WindowsError exceptions; instead raise a new exception.
29    # TODO: try to incorporate current stack trace in the raised exception
30    if isinstance(exc, WindowsError):
31        raise OSError(str(exc)+msg)
32
33    args = exc.args
34    if not args:
35        exc.args = (msg,)
36    else:
37        try:
38            arg0 = " ".join((args[0],msg))
39            exc.args = tuple([arg0] + list(args[1:]))
40        except:
41            exc.args = (" ".join((str(exc),msg)),)
Note: See TracBrowser for help on using the repository browser.