Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bypass error and continue code

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.

like image 890
theage Avatar asked Apr 05 '14 21:04

theage


1 Answers

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'
like image 183
Dunno Avatar answered Sep 30 '22 01:09

Dunno