Main Content

Elements of an exception in Python - try, except, else, finally

Archive - Originally posted on "The Horse's Mouth" - 2015-02-28 14:45:53 - Graham Ellis

All the elements of an exception handler in one example ... [here]

try - enters at the top and continues through the block
except - jump to there is an exception is thrown
else - run after the try block completes without exception thrown
finally - always run after the other blocks have completed

A correctly running block
try - else - finally
(and code loops completes)

  -bash-4.1$ python duff
  (bfor) Exception demonstration
  
  (try-) Please enter a Python value: 44
  (else) Input accepted
  (finl) Tidying up
  
  (done) Value received: 44
  -bash-4.1$


A block with an error
try - except - finally
(and code loops back to have another go)

  -bash-4.1$ python duff
  (bfor) Exception demonstration
  
  (try-) Please enter a Python value: forty
  (exce) Not acceptable!
  (exce) Message: name 'forty' is not defined
  (exce) Failure Type: NameError
  (finl) Tidying up
  
  (try-) Please enter a Python value:


Code

  while True:
    try:
      n = input("(try-) Please enter a Python value: ")
    except KeyboardInterrupt:
      print "(ex/k) You give up?"
      print "(ex/k) Won't break me that way"
    except Exception,e:
      print "(exce) Not acceptable!"
      print "(exce) Message: ",e
      print "(exce) Failure Type:",e.__class__.__name__
    else:
      print "(else) Input accepted"
      break
    finally:
      print "(finl) Tidying up\n"