4

I have python code that catches an exception:

# ...
except Exception:
    # Handle the exception

When this code is executed, the traceback (stack trace) is printed to the console. How can I suppress it?

Raffi Khatchadourian
  • 3,042
  • 3
  • 31
  • 37
  • 6
    Show the rest of the handling code... it shouldn't be printed. – agf Sep 20 '11 at 23:01
  • 1
    How are you running this code? Can you post the stack trace that gets printed? Are you sure you're catching the exception? Normally Python will only print a stack trace for exceptions that make it to the program's entry point. – Peter Graham Sep 20 '11 at 23:32
  • 3
    Ah you sure the exception that's being printed is the original exception? If another exception happens inside your exception handler, it will propagate outwards and it can sometimes be difficult to spot that it's not the original cause of things going wrong. – Ben Sep 21 '11 at 03:06
  • @Ben I think you are right. I think that is what is happening. – Raffi Khatchadourian Oct 03 '11 at 16:20
  • an old question, I know, but this is at least the answer I was looking for: https://stackoverflow.com/a/27674608/2184122 – Robert Lugg Jan 11 '18 at 21:23

1 Answers1

6

Not recommended, but

except Exception:
    pass

Will silently ignore the exception. However, if you don't fix what went wrong, your program may quit anyways because something further down in your code will throw another exception. You should at the least print out a message stating what happened, or debugging your code can be a nightmare.

brc
  • 5,281
  • 2
  • 29
  • 30
  • 1
    Well, I want to handle the exception but I don't want the stack trace to print. In Java, the stack trace prints when the printStackTrace method is called. Not calling that method suppresses the stack trace being printed, however, I am not sure how that's done in Python. – Raffi Khatchadourian Sep 26 '11 at 23:36
  • 1
    The given code will skip the stack trace printing. The python analog to `printStackTrace` is [sys.exc_info](http://docs.python.org/library/sys.html#sys.exc_info). – brc Sep 27 '11 at 00:25