Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute something if any exception happens

A python newbie question: 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 this. But is there a cleaner way of doing this?

like image 393
amit Avatar asked Nov 11 '10 05:11

amit


People also ask

How do you define actions that should be executed when there was no exception in the try block in Python?

The try statement works as follows. First, the try clause (the statement(s) between the try and except keywords) is executed. If no exception occurs, the except clause is skipped and execution of the try statement is finished. If an exception occurs during execution of the try clause, the rest of the clause is skipped.

How do I run an exception in Python?

As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword.

What happens when exception occurs?

Definition: An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. When an error occurs within a method, the method creates an object and hands it off to the runtime system.

Does try except stop execution?

The try… except block is completed and the program will proceed. However, if an exception is raised in the try clause, Python will stop executing any more code in that clause, and pass the exception to the except clause to see if this particular error is handled there.


2 Answers

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

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

try:
    input("]")  # for Python 3: eval(input("]"))
except:
    try:
       #Here do something if any exception was thrown.
       raise
    except SyntaxError:
       print "?SYNTAX",
    except ValueError:
       print "?ILLEGAL QUANTITY",
    # additional handlers here
    except:
       print "?UNKNOWN",
    finally:
       print "ERROR"
like image 88
kindall Avatar answered Oct 12 '22 01:10

kindall


I just tried a couple different idea's out and it looks like a flag is your best bet.

  • else suite is only called if there is no exception
  • finally will always be called
like image 43
David Avatar answered Oct 12 '22 01:10

David