Python
  Home arrow Python arrow Page 7 - 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 - Raising The Bar
    ( Page 7 of 9 )

    Thus far, you've been working with Python's built-in exceptions, which can handle most logical or syntactical expressions. However, Python also allows you to get creative with exceptions, by generating your own custom exceptions if the need arises.

    This is accomplished via Python's "raise" statement, which is used to raise errors which can be detected and resolved by the "try" family of exception handlers. The "raise" statement needs to be passed an exception name, and an optional descriptive string. When the exception is raised, this exception name and description will be made available to the defined exception handler.

    Let's go to a quick example - the line of code

    raise ValueError, "What on earth are you thinking?!"
    generates the following error.

    Traceback (innermost last): File "./test.py", line 3, in ? raise ValueError, "What on earth are you thinking?!" ValueError: What on earth are you thinking?!
    You can also name and use your own exceptions.

    #!/usr/bin/python

    import os

    # define error object error = "someError"

    # function to raise error def checkName(name): if (name != os.environ["USER"]): raise error, "Username mismatch!"

    name = raw_input("Enter your system username: ") checkName(name)
    In this case, if the username entered at the prompt does not match the name stored in the environment variable $USER, Python will raise a user-defined exception named "someError", with a string of text describing the nature of the error. Take a look:

    Enter your system username: john Traceback (innermost last): File "checkuser.py", line 16, in ? checkName(name) File "checkuser.py", line 11, in checkName raise error, "Username mismatch!" someError: Username mismatch!
    Note that the exception must be assigned to an object in order for it to work correctly.

    # define error object error = "someError"
    Trapping user-defined errors is exactly the same as trapping pre-defined Python errors. The following refinement of the code above illustrates this:

    #!/usr/bin/python

    import os

    # define error object error = "someError"

    # function to raise error def checkName(name): if (name != os.environ["USER"]): raise error, "Username mismatch!"

    # try this code try: name = raw_input("Enter your system username: ") checkName(name) except error, desc: print desc
    Here's the output of the script above, when the wrong username is entered.

    Enter your system username: john Username mismatch!


     
     
    >>> 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 1 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek