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