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!