Home arrow Python arrow Page 7 - Python 101 (part 8): An Exceptionally Clever Snake

Raising The Bar - Python

In this concluding article of the Python 101 series, find out howto use Python's exception-handling routines to trap and resolve programerrors, learn to generate and use custom error messages, and get acquainteda bunch of useful (and free!) Python resources online.

TABLE OF CONTENTS:
  1. Python 101 (part 8): An Exceptionally Clever Snake
  2. Anatomy Of An Exception
  3. Trying Harder
  4. Different Strokes
  5. Passing The Buck
  6. Bad Boys
  7. Raising The Bar
  8. Strong Pythons (And The Exceptions That Love Them)
  9. The End Of The Affair
By: Vikram Vaswani, (c) Melonfire
Rating: starstarstarstarstar / 8
August 23, 2001

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

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

This is accomplished via Python's "raise" statement, which is used to raiseerrors which can be detected and resolved by the "try" family of exceptionhandlers. The "raise" statement needs to be passed an exception name, andan optional descriptive string. When the exception is raised, thisexception name and description will be made available to the definedexception 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 namestored in the environment variable $USER, Python will raise a user-definedexception named "someError", with a string of text describing the nature ofthe 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 towork correctly.

# define error object error = "someError"
Trapping user-defined errors is exactly the same as trapping pre-definedPython 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
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PYTHON ARTICLES

- Python Big Data Company Gets DARPA Funding
- Python 32 Now Available
- Final Alpha for Python 3.2 is Released
- Python 3.1: String Formatting
- Python 3.1: Strings and Quotes
- Python 3.1: Programming Basics and Strings
- 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

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: