views:

54

answers:

2

I know try/except can handle errors in my program. But, is there a way of making the error be displayed in the program execution, be ignored and let the execution go on?

+2  A: 
import traceback

try:
    # do whatever you want
except Exception:
    traceback.print_exc()

Of course you should be more specific in a real scenario, i.e. you shouldn't catch and ignore all Exception instances, only the ones you are interested in and you know that they are safe to ignore.

Also note that if an exception happens somewhere within the try..except block, the execution will continue after the try..except block, not at the next statement. This is probably the closest to what you want to achieve.

Tamás
Thanks! That was really helpful!
FRD
+1  A: 

In VBScript and other VB-derived languages, you can get this sort of behavior with "ON ERROR GOTO NEXT".

No such behavior exists in Python. Even if you wrap each top-level statement like:

try:
  do_something()
except Exception as e:
  print e

try:
  do_something_else()
except Exception as e:
  print e

you'd still have the result that statements within do_something are skipped at the point the exception is thrown.

Though perhaps if you have a particular use-case in mind, there may be other acceptable answers. For instance, in a top-level loop:

while True:
  cmd = get_command()
  if cmd == 'quit': break
  try:
    run_command(cmd)
  except Exception as e:
    print "Error running " + cmd + ":"
    print e
Adam Vandenberg