python try: except: pass; on multi line try statements

18,197

Solution 1

Python doesn't allow you to re-enter a failed block. Instead, you can make a nested try block:

try:
    print "before"
    try:
        print d['not-exist']
    except KeyError:
        pass
    print "after"
except OtherError:
    print "OtherError"

Note that you can often avoid KeyErrors using .get:

try:
    x = d['key']
except KeyError:
    x = 0

is equivalent to

x = d.get('key', 0)

In general, try to make your try blocks as short as logically possible, so you have a better chance of dealing with the errors in an appropriate, localized fashion.

Solution 2

You can also use 'else' to a try/except block:

d={'a':1, 'b':2, 'd':4}

for k in 'abcd':
     try:
        print k, d[k],
     except KeyError:
        print '{} not there'.format(k)
     else:
        print 'I did it! Found {}'.format(k)   

Prints:

a 1 I did it! Found a
b 2 I did it! Found b
c c not there
d 4 I did it! Found d

In general, the full try/except/else/final set go like this:

try:
    potential_error()
except ExceptionType:
    handle_that_error_somehow()
else:                            # 'else' to the except is SUCCESS
    # There was no error
    # handle success!
    handle_success()
finally:
    # success or failure -- do this
    regardless_something_we_always_need_to_do()    

Solution 3

python supports finally blocks, which will be executed even if there is an exception in the try block:

try:
  print "entering try block"
  print this_var_does_not_exists
except:
  pass
finally:
  print "past exception"

Solution 4

You can't do it with that structure. You'd need to move the extra print out of the try block. The way a try/except block works is that if an exception is raised it jumps to the appropriate except block. There's no way to go back. If you want to continue, you need to put your code either in the except or a finally, or after the whole block. Here's one example:

try:
  print "entering try block"
  print this_var_does_not_exists
finally:
  print "past exception"

Also, don't form the dangerous habit of using bare except: clauses, especially with pass as their only content. You should catch the kinds of exceptions you can handle, and then handle them, not blindly silence all exceptions.

Share:
18,197

Related videos on Youtube

wholly_cow
Author by

wholly_cow

Updated on June 16, 2022

Comments

  • wholly_cow
    wholly_cow almost 2 years

    I have a block of statements in a try: except KeyError: pass block and wanted to know how I could have Python attempt to execute the code after the line that throws the exception.

    For e.g

    try:
      print "entering try block"
      print this_var_does_not_exists
      print "past exception"
    except:
      pass
    

    I want to try and print "past exception".

    When I run the above code it only prints 'entering try block'

  • wholly_cow
    wholly_cow over 10 years
    Awesome. Thats what I needed! - .get :)

Related