Ernesto wrote:

> Within the scope of one Python file (say myFile.py), I'd like to print
> a message on ANY exception that occurs in THAT file, dependent on a
> condition.

    condition = True

    def handle_any_exception(function):
        def trampoline(*args, **kwargs):
            try:
                return function(*args, **kwargs)
            except:
                if not condition:
                    raise
                print "exception caught in", function.__name__
                return "n/a" # default return value
        return trampoline

    @handle_any_exception
    def myfunc(x):
        return 1 / x

    @handle_any_exception
    def myotherfunc(filename):
        return open(filename)

    class MyClass:
        @handle_any_exception
        def mymethod(self):
            raise ValueError("oops")

    myfunc(1)
    myfunc(0)
    myotherfunc("hello.txt")
    MyClass().mymethod()

</F> 



-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to