By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,645 Members | 1,047 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,645 IT Pros & Developers. It's quick & easy.

What's the best way to wrap a whole script in try..except?

P: n/a
I want to wrap a whole script in try ... except. What is the best way of
doing this?

Consider the following: -

try:
import <modules>

<CODE>

def notifyme(traceback):
code to tell me there is a problem

except Exception, traceback:
notifyme(traceback)
Would this code not work because if any part of <CODE> encounters an
exception then it won't reach the notifyme() function definition and
therefore the whole thing won't work and I won't get notified when a
traceback occurs, in fact the call to notifyme() under except will
itself probably trace back as well!

Do I have to instead do:

import <a couple of modules>
def notifyme():
code to tell me there is a problem

try:
<CODE>

except Exception, traceback:
notifyme(traceback)
How you you handle this?
Hari
Jun 21 '06 #1
Share this Question
Share on Google+
2 Replies


P: n/a
In article <ma***************************************@python. org>, Hari Sekhon wrote:
I want to wrap a whole script in try ... except. What is the best way of
doing this?


You could do this maybe:

import sys

def excepthook(exc_type, exc_value, tb):
import modules_needed_to_notify_exception
...

sys.excepthook = excepthook

import modules_needed_by_script
...
Jun 21 '06 #2

P: n/a
Hari Sekhon wrote:
I want to wrap a whole script in try ... except. What is the best way of
doing this?

Consider the following: -

try:
import <modules>

<CODE>

def notifyme(traceback):
code to tell me there is a problem

except Exception, traceback:
notifyme(traceback)
Would this code not work because if any part of <CODE> encounters an
exception then it won't reach the notifyme() function definition and
therefore the whole thing won't work and I won't get notified when a
traceback occurs, in fact the call to notifyme() under except will
itself probably trace back as well!
Yes.
Do I have to instead do:

import <a couple of modules>
def notifyme():
code to tell me there is a problem

try:
<CODE>

except Exception, traceback:
notifyme(traceback)

Would work, but...
How you you handle this?


I don't put the main logic at the top level - I use a main() function.

import <some modules>
def notifyme(e):
# code here...

def main(*args):
try:
# code here
return 0

except Exception, e:
notifyme(e)
return <some-non-zero-error-code>

if __name__ == '__main__':
import sys
sys.exit(main(*sys.argv))

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Jun 21 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.