Hello--
I have a long-running program on a remote machine and want to be sure that (1) I have a record of any exception that causes it to terminate and (2) someone is notified if it terminates. Does anyone see drawbacks to the method I am using? (or have recommendations for a better one?)
I've read the Python docs and many exception-related posts here, and understand that blanket except clauses are usually a bad idea. Within subroutines and modules I always use except to handle specific expected exceptions, but it seems useful to have a "catch-all" except clause at the highest level of the program to ensure I can log the exception before the program exits.
What do you think?
import traceback
try:
# main program code here
except BaseException:
tb = traceback.format_exc()
msg = "Exiting program due to exception:" + tb
LogToFile(msg) # custom logging function
SendAlertEmail(msg) # warn admin that program terminated
raise # program exits with the existing exception
Note that I was using BaseException instead of Exception because if someone at the terminal presses Ctrl-C, I would like to log that as the reason for exiting the program (and alert an admin that the program was exited). But I suppose I could also use:
except Exception, KeyboardInterrupt: