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 str_(e, with_name=True):
21
    msg = strings.ensure_newl(str(e))
22
    if with_name: msg = util.type_name(e)+': '+msg
23
    return msg
24

    
25
def print_ex(e, **format): sys.stderr.write('! '+str_(e, **format))
26

    
27
class ExTracker:
28
    def __init__(self):
29
        self.e_ct = 0
30
        def at_exit():
31
            if self.e_ct > 0:
32
                raise SystemExit('Encountered '+str(self.e_ct)+' error(s)')
33
        atexit.register(at_exit)
34
    
35
    def track(self, e, **format):
36
        self.e_ct += 1
37
        print_ex(e, **format)
(4-4/13)