Global "except" condition

E

Ernesto

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.

Here's the pseudocode:

if anyExceptionOccurs():
if myCondition:
print "Here's my global exception message"


Is this functionality possible in python? If so, how?
 
S

Simon Forman

Ernesto said:
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.

Here's the pseudocode:

if anyExceptionOccurs():
if myCondition:
print "Here's my global exception message"


Is this functionality possible in python? If so, how?

Either wrap all your module level code in a try:.. except:.. statement,
or you can replace the sys.excepthook() function with your own custom
function (see http://docs.python.org/lib/module-sys.html) but that
would then be called for all uncaught exceptions, even those that were
raised from modules other than your myFile.py.

HTH,
~Simon
 
S

Steve Holden

Ernesto said:
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.

Here's the pseudocode:

if anyExceptionOccurs():
if myCondition:
print "Here's my global exception message"


Is this functionality possible in python? If so, how?
What if your module defines a function, and then that function is called
from some other module and raises an exception. Would you then want the
global exception message to appear?

If so then I'm not sure that what you want is possible.

regards
Steve
 
F

Fredrik Lundh

Ernesto said:
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>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,430
Messages
2,571,676
Members
48,796
Latest member
Greg L.

Latest Threads

Top