Exception Handling in Python
- lots of things can cause errors in Python
- invalid arguments to functions
- bad type of input from user
- opening files for input that don't exist
- dividing by zero
- usually can use an if to prevent the errors
- always check for denominator of zero before doing division!
- check for negatives before calling sqrt
- check a string that is input before converting it to a number
- some are difficult to test for with an if
- can use Python's own error-handling mechanism
- called "exception handling" "it's the exception not the rule"
- an exception tells Python how you want the program to handle the error
- in Python, the syntax uses two new keywords
- "try:" on a line by itself
- followed by a block of code indented underneath it
- and "except:" on a line by itself
- followed by a block of code indented underneath it
- except can have an error name after it on the line
- will "trap" only that error
- can have several "except blocks" for different errors
- except: by itself means "catch all errors"
- semantics: if the "try block" does not have an error, all except blocks
are skipped and execution continues after those blocks
- if the try block has an error, if it is an error that is trapped
by the except, then that block of code is executed. Then code after all of the
except blocks is executed.
- If it is not the
error that is trapped by the except, then the standard Python behavior
happens (big red message with traceback and crash)
Documentation about Exceptions look for 5.2. Concrete exceptions to find the list
Some Error names - watch capitalization!
- ZeroDivisionError
- ValueError = argument has the right type but inappropriate value
- TypeError = operation applied to object of inappropriate type
- IndexError = sequence subscript is out of range - does not check slices
- IOError = file problem, such as "file not found"
Try to keep the "try block" as small and focused as possible,
so that you only have to check for an error or two. Putting your entire
program in a "try block" may stop it from crashing, BUT you will have to
figure out which error caused the exception, and do something useful for it.
Examples:
Getting a valid filename
def main():
fn = input("Enter a filename ")
IOok = False
while not IOok:
try:
infile = open(fn,"r")
IOok = True
except IOError:
print("Error, file would not open")
fn = input("Enter a filename ")
# at this point infile is a valid file, open for reading
# and fn is the external name for the file
main()
example of error caused by division by zero
def main():
try:
x = 0
y = 7
print(y/x)
except:
print("x was 0")
print("next")
main()
Example of more than one error caught
from math import *
def main():
try:
x = -10
y = 7
print(sqrt(y/x))
except ZeroDivisionError:
print("dividing by zero!")
except ValueError:
print("sqrt does not take negatives")
print("last")
main()