Python
  Home arrow Python arrow Page 3 - Python 101 (part 8): An Exceptionally Clever Snake
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
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? 
Google.com  
PYTHON

Python 101 (part 8): An Exceptionally Clever Snake
By: Vikram Vaswani, (c) Melonfire
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 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:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log 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


    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 appropriate exception-handling code depending on the exception type. It's a lot like the "if-elif-else" conditional construct, allowing for the execution of different 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, it first attempts to execute the code within the "try" block. If this code is processed without any exceptions being generated, Python checks to see if the optional "else" block is present. If it is, the code within it is executed.

    If an exception is encountered while running the code within the "try" block, Python stops execution of the "try" block at that point and begins checking each "except" block to see if there is a handler for the exception. 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 and displays a stack trace.

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

    Let's illustrate this with a simple Python program, which accepts two numbers 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 knows how 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 exception handler is triggered and an error message displayed. The optional "else" block is executed at the end of the script *only* if no exceptions are encountered.

    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

    - Tuples and Other Python Object Types
    - The Dictionary Python Object Type
    - String and List Python Object Types
    - Introducing Python Object Types
    - Mobile Programming using PyS60: Advanced UI ...
    - Nested Functions in Python
    - Python Parameters, Functions and Arguments
    - Python Statements and Functions
    - Statements and Iterators in Python
    - Sequences and Sets in Python
    - Python Expressions and Operators
    - Dictionaries, Variables and Statements in Py...
    - Data Types in Python
    - The Python Language
    - SSH with Twisted





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 4 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek