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.
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!