[Tutor] question about try & except

Kent Johnson kent37 at tds.net
Thu Oct 27 13:50:23 CEST 2005


w chun wrote:
> if your app is willing to tolerate errors/crashes, then i would take
> alan's advice and just letting the errors happen, as opposed to being
> so careful with (and integrating Kent's suggestion for the full
> traceback with):
> 
> try:
>     BLOCK
> except Exception, e:
>     print e, traceback.print_exc()
>     # take some other evasive yet safe maneuver

No, not quite. print_exc() does its own output and returns None, so it shouldn't be part of the print statement. And print_exc() prints e as part of its output, so 'print e' is redundant. All you need in the except block is traceback.print_exc() and whatever additional handling you want to do.

Normally it's not a good idea to catch generic Exception - you usually can be more focused than that - but at a high level in an application it can be useful to catch everything. For example you may be processing a list of files in a loop and you don't want an error in one file to abort the loop. So you put a try / except at the top level of the loop to catch and log errors, then continue with the next file.

Kent



More information about the Tutor mailing list