Thursday, August 30, 2012

Teach me how to fish - python exception handling

I really do want to understand this documentation: from `pydoc try`

The ``try`` statement
*********************

The ``try`` statement specifies exception handlers and/or cleanup code
for a group of statements:

   try_stmt  ::= try1_stmt | try2_stmt
   try1_stmt ::= "try" ":" suite
                 ("except" [expression ["as" target]] ":" suite)+
                 ["else" ":" suite]
                 ["finally" ":" suite]
   try2_stmt ::= "try" ":" suite
                 "finally" ":" suite
So what exactly does the first line mean?
try_stmt  ::= try1_stmt | try2_stmt
. It's a bit confusing as I know how to implement very simple try statements like this;
try:
    import io
    print("importing io")
except ImportError:
    print("nothing to import")
    foo = None
try:
    import somefunctionthatdoesnotexist
    print("importing ...")
except ImportError:
    print("nothing to import")
    foo = None

2 comments:

  1. joined the python tutor mailing list. Hopelfully, someone will be able to explain it to me or at least get me to bootstrap my understanding of this doc.

    ReplyDelete
  2. Ah. Thanks to the chaps at the python tutor mailing list!

    This is just BNF, explaining the syntax

    http://en.wikipedia.org/wiki/Backus%E2%80%93Naur_Form ;-)

    ReplyDelete