SunQuest
 
       Python
  Home arrow Python arrow Page 3 - Python 101 (part 8): An Exceptionally ...
Dev Shed Forums 
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Sun Developer Network 
Dedicated Servers 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Actuate Whitepapers 
VeriSign Whitepapers 
VPS Hosting 
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PYTHON

Python 101 (part 8): An Exceptionally Clever Snake
By: Vikram Vaswani, (c) Melonfire
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 8
    2001-08-23

    Table of Contents:
  • Python 101 (part 8): An Exceptionally Clever Snake
  • Anatomy Of An Exception
  • Trying Harder
  • Different Strokes
  • Passing The Buck
  • Bad Boys
  • Raising The Bar
  • Strong Pythons (And The Exceptions That Love Them)
  • The End Of The Affair

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT

    Stay one step ahead of the competition. Evaluate and give feedback on some of the hottest web development tools on the market today. Make your opinion heard! Click Here

    Python 101 (part 8): An Exceptionally Clever Snake - Trying Harder


    (Page 3 of 9 )

    Python offers two flavours of exception handler - the first is the"try-except" construct you just saw, while the second is the "try-finally"construct.

    The "try-except" construct - actually the "try-except-else" construct -allows developers to trap different types of errors and execute appropriateexception-handling code depending on the exception type. It's a lot likethe "if-elif-else" conditional construct, allowing for the execution ofdifferent code blocks depending on the type of error generated.

    The structure of a "try-except-else" block looks like this:

    try: execute this block except err1: execute this block if exception "err1" is generated except err2: execute this block if exception "err2" is generated

    ... and so on ...

    else: execute this block
    When Python encounters code wrapped within a "try-except-else" block, itfirst attempts to execute the code within the "try" block. If this code isprocessed without any exceptions being generated, Python checks to see ifthe optional "else" block is present. If it is, the code within it isexecuted.

    If an exception is encountered while running the code within the "try"block, Python stops execution of the "try" block at that point and beginschecking each "except" block to see if there is a handler for theexception. If a handler is found, the code within the appropriate "except"block is executed; if not, control either moves to the parent "try" block,if one exists, or to the default handler, which terminates the program anddisplays a stack trace.

    Once the "try" block has been executed and assuming that the program hasnot been terminated, the lines following the "try" block are executed.

    Let's illustrate this with a simple Python program, which accepts twonumbers and attempts to divide them by each other.

    #!/usr/bin/python

    alpha = input("Gimme a number: ") beta = input("Gimme another number: ") gamma = alpha / beta print alpha, "divided by", beta, "is", gamma
    Now look what happens when I run this with different values.

    Gimme a number: 10 Gimme another number: 2 10 divided by 2 is 5

    Gimme a number: 10 Gimme another number: 0 Traceback (innermost last): File "div.py", line 6, in ? gamma = alpha / beta ZeroDivisionError: integer division or modulo

    Gimme a number: 67347328 Gimme another number: 943282646373739 Traceback (innermost last): File "div.py", line 4, in ? beta = input("Gimme another number: ") OverflowError: integer literal too large

    Let's now add a couple of exception handlers to this code, so that it knowshow to gracefully handle errors like the ones above:

    #!/usr/bin/python

    try: alpha = input("Gimme a number: ") beta = input("Gimme another number: ") gamma = alpha / beta print alpha, "divided by", beta, "is", gamma except ZeroDivisionError: print "Cannot divide by zero!" except OverflowError: print "Number too large!" else: print "No errors encountered!"

    print "-- All done --"
    And now let's try the different test cases above again:

    Gimme a number: 10 Gimme another number: 2 10 divided by 2 is 5 No errors encountered! -- All done --

    Gimme a number: 10 Gimme another number: 0 Cannot divide by zero! -- All done --

    Gimme a number: 823748237 Gimme another number: 234378264732647326476327 Number too large! -- All done --

    Depending on the type of error encountered, the appropriate exceptionhandler is triggered and an error message displayed. The optional "else"block is executed at the end of the script *only* if no exceptions areencountered.

    Once an exception has been caught and resolved, the remainder of the "try"block is ignored and Python executes the lines following the entire"try-except-else" block.

    More Python Articles
    More By Vikram Vaswani, (c) Melonfire


     

       

    PYTHON ARTICLES

    - SSH with Twisted
    - Mobile Programming in Python using PyS60: UI...
    - Python: Count on It
    - Python Strings: Spinning Yarns
    - Python: More Fun with Strings
    - Python: Stringing You Along
    - Python Operators
    - Bluetooth Programming in Python: Network Pro...
    - Python Sets
    - Python Conditionals, Lists, Dictionaries, an...
    - Python: Input and Variables
    - Introduction to Python Programming
    - Mobile Programming in Python using PyS60: Ge...
    - Bluetooth Programming using Python
    - Finishing the PyMailGUI Client: User Help To...





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 6 hosted by Hostway