12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Why You Will Care: Error ChecksOne way to see how exceptions are useful is to compare coding styles in <strong>Python</strong> andlanguages without exceptions. For instance, if you want to write robust programs inthe C language, you generally have to test return values or status codes after every operationthat could possibly go astray, and propagate the results of the tests as yourprograms run:doStuff( ){ # C programif (doFirstThing( ) == ERROR) # Detect errors everywherereturn ERROR;# even if not handled hereif (doNextThing( ) == ERROR)return ERROR;...return doLastThing( );}main( ){if (doStuff( ) == ERROR)badEnding( );elsegoodEnding( );}In fact, realistic C programs often have as much code devoted to error detection as todoing actual work. But in <strong>Python</strong>, you don’t have to be so methodical and neurotic.You can instead wrap arbitrarily vast pieces of a program in exception handlers, andsimply write the parts that do the actual work, assuming all is well:def doStuff( ): # <strong>Python</strong> codedoFirstThing( ) # We don't care about exceptions here,doNextThing( ) # so we don't need to detect them...doLastThing( )if_ _name_ _ == '_ _main_ _':try:doStuff( ) # This is where we care about results,except:# so it's the only place we must checkbadEnding( )else:goodEnding( )Because control jumps immediately to a handler when an exception occurs, there’s noneed to instrument all your code to guard for errors. Moreover, because <strong>Python</strong> detectserrors automatically, your code usually doesn’t need to check for errors in the firstplace. The upshot is that exceptions let you largely ignore the unusual cases and avoiderror-checking code.with/as Context Managers | 599

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!