How to execute something if any exception occurs

Newbie question in python: I need to do the following

try: do-something() except error1: ... except error2: ... except: ... #Here I need to do something if any exception of the above exception was thrown. 

I can set a flag and do it. But is there a cleaner way to do this?

+7
python exception-handling
source share
6 answers

I just tried a couple of different ideas, and it seems your best bet is the flag.

  • else suite is called only if there is no exception
  • finally will always be called
+2
source share

You can do this with a nested try. The except block of an external try should catch all exceptions. His body is another try that immediately repeats the exception. The except blocks of internal try actually handle individual exceptions. You can use the finally block in internal try to do what you want: run something after any exception, but only after the exception.

Here is a small interactive example (modeled on Applesoft BASIC for nostalgia).

 try: input("]") # for Python 3: eval(input("]")) except: try: raise except SyntaxError: print "?SYNTAX", except ValueError: print "?ILLEGAL QUANTITY", # additional handlers here except: print "?UNKNOWN", finally: print "ERROR" 
+2
source share

From the docs: http://docs.python.org/reference/compound_stmts.html#finally

If finally is present, it indicates a "cleanup handler." The try clause is executed, including any except and else clauses. If an exception occurs in any of the sentences and is not processed, the exception is temporarily saved. The finally clause is executed. If there is a stored exception, it will be raised again at the end of the finally clause. If the finally clause raises another exception or executes a return or break statement, the saved exception will be lost. Exception information is not available to the program during the execution of the finally clause.

+1
source share

In fact, I do not like flags and consider them the last decision. In this case, I would think something like this:

 def f(): try: do_something() except E1: handle_E1() except E2: handle_E2() else: return do_stuff_to_be_done_in_case_any_exception_occurred() 

Of course, this is only an option if you can return in the case of else:

Another option might be to rebuild the exception and execute it for more general error handling. This may even be the cleanest approach:

 def f(): try: # general error handling try: # specific error handling do_something() except E1: handle_E1() raise except E2: handle_E2() raise except (E1, E2): do_stuff_to_be_done_in_case_any_exception_occurred() 
+1
source share

It is not clear whether error1, error2, etc. should be handled differently. If not, the following code will do the trick:

 try: do_something() except (error1, error2, error3), exception_variable: handle_any_of_these_exceptions() 

if you need to handle different errors in different ways, as well as have a common code, then in the except block you can have the code of the following type:

  if isinstance(exception_variable, error1): do_things_specific_to_error1() 
0
source share

This is the best way I can think of. Looks like the smell of code though

 try: exception_flag = True do-something() exception_flag = False except error1: ... except error2: ... except: ... finally: if exception_flag: ... 

You will not need finally if you do not reraise exceptions in the handler

0
source share

All Articles