Project

General

Profile

1
# Exception handling
2

    
3
import atexit
4
import sys
5

    
6
import strings
7
import util
8

    
9
def add_msg(e, msg): e.args = (strings.ensure_newl(str(e))+msg,)
10

    
11
def repl_msg(e, **repls): e.args = (str(e) % repls,)
12

    
13
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

    
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
    sys.stderr.write('! '+msg)
22

    
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)
(3-3/11)