Project

General

Profile

1
# Exception handling
2

    
3
import atexit
4
import sys
5

    
6
import strings
7
import util
8

    
9
def raise_(e): raise e
10

    
11
def add_msg(e, msg): e.args = (strings.ensure_newl(str(e))+msg,)
12

    
13
def repl_msg(e, **repls): e.args = (str(e) % repls,)
14

    
15
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

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

    
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)
(4-4/13)