Project

General

Profile

1 11 aaronmk
# Exception handling
2
3 433 aaronmk
import atexit
4 343 aaronmk
import sys
5 13 aaronmk
6 343 aaronmk
import strings
7
import util
8
9 445 aaronmk
def raise_(e): raise e
10
11 343 aaronmk
def add_msg(e, msg): e.args = (strings.ensure_newl(str(e))+msg,)
12
13 286 aaronmk
def repl_msg(e, **repls): e.args = (str(e) % repls,)
14 279 aaronmk
15 13 aaronmk
class ExceptionWithCause(Exception):
16
    def __init__(self, msg, cause=None):
17
        Exception.__init__(self, msg)
18
        if cause != None: add_msg(self, 'cause: '+str(cause))
19 343 aaronmk
20
def print_ex(e, with_name=True):
21
    msg = strings.ensure_newl(str(e))
22
    if with_name: msg = util.type_name(e)+': '+msg
23 366 aaronmk
    sys.stderr.write('! '+msg)
24 433 aaronmk
25
class ExTracker:
26
    def __init__(self):
27
        self.e_ct = 0
28
        def at_exit():
29
            if self.e_ct > 0:
30
                raise SystemExit('Encountered '+str(self.e_ct)+' error(s)')
31
        atexit.register(at_exit)
32
33
    def track(self, e, **format):
34
        self.e_ct += 1
35
        print_ex(e, **format)