5

This was a simple problem I was having earlier. Essentially, solutions like this and this to "ignoring" an exception really don't. Even if they don't crash python anymore, they still stop whatever code was in the initial try clause.

try:
    assert False
    print "hello"
except AssertionError:
    pass

This code will not print "hello", but rather skip over it, going to the pass. My question is, is there an easy way to truly ignore this in Python 2.7? I read about some things going on in 3.4 to make this easier, but I'd rather stay with python 2.7.

Community
  • 1
  • 1
theage
  • 289
  • 1
  • 3
  • 10
  • It looks like you have some design problem in your program. Can you please describe why do you need such exception ignoring? – Messa Apr 05 '14 at 21:24
  • This is a good argument for having *only the code you think could fail* in the `try` block – jonrsharpe Apr 05 '14 at 21:25

3 Answers3

4

I don't think you can, and I don't think you should.

Errors should never pass silently.
Unless explicitly silenced.

Zen of Python

It means that it's your duty as a programmer to think where and why exceptions might arise. You should (have to, actually) avoid the temptation to put a long block of code in a try statement and then think about exceptions. The correct thought flow is:

  1. Write assert False
  2. Notice that it might raise an AssertionError
  3. Put assert False in a try...except... block
  4. Write print 'Hello'
  5. Notice that this line will not cause any errors (famous last words, by the way)
  6. Profit

So your code should look like this (other answers are pretty nice, too):

try:
    assert False
except AssertionError:
    pass
print 'Hello'
Dunno
  • 3,632
  • 3
  • 28
  • 43
3

You can use finally:

try:
    assert False
    print "Hello"
except AssertionError:
    pass
finally:
    print "This prints no matter what"

This prints no matter what

If you want to execute a code block in the case the error does not occur you can use the try except else construct.

shaktimaan
  • 11,962
  • 2
  • 29
  • 33
1

Move what you want to happen if the error doesn't occur to an else block:

try:
    assert False
except AssertionError:
    print "error"
else:
    print "no error"
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437