Lecture 30
Lecture 30
Lecture 30
Lecture Outline
• Exception handling
– CS1001 Lecture 30 –
Exception handling
– CS1001 Lecture 30 – 1
try...except
try:
<body>
except <ExceptionType>:
<handler>
– CS1001 Lecture 30 – 2
Example: FileNotFoundError
def main():
askFile = True
while askFile:
try:
filename = input("Enter a filename: ").strip()
infile = open(filename, "r") # Open the file
askFile=False
except FileNotFoundError:
print("File " + filename + " does not exist. Try again.")
# Display results
for i in range(len(counts)):
if counts[i] != 0:
print(chr(ord(’a’) + i) + " appears " + str(counts[i])
+ (" time" if counts[i] == 1 else " times"))
– CS1001 Lecture 30 – 3
Example: FileNotFoundError
– CS1001 Lecture 30 – 4
Multiple exceptions
– CS1001 Lecture 30 – 5
Multiple exceptions
try:
<body>
except <ExceptionType1>:
<handler1>
...
except <ExceptionTypeN>:
<handlerN>
except:
<handlerExcept>
else:
<process_else>
finally:
<process_finally>
– CS1001 Lecture 30 – 6
Multiple exceptions
– CS1001 Lecture 30 – 7
Exception classes
– CS1001 Lecture 30 – 8
Exception classes
• Some of the built-in exception classes in Python:
BaseException
Exception
ZeroDivisionError IndentationError
IndexError
KeyError
– CS1001 Lecture 30 – 9
Example: division
def main():
try:
number1, number2 = eval(input("Enter two numbers: "))
result = number1 / number2
print("The result is: " + str(result))
except ZeroDivisionError:
print("Division by zero!")
except SyntaxError:
print("A comma may be missing in the input")
except:
print("Something wrong in the input")
else:
print("No exceptions")
finally:
print("The finally clause is executed")
main()
– CS1001 Lecture 30 – 10
Example: division
• Sample runs:
– CS1001 Lecture 30 – 11
Raising exceptions
or
raise ExceptionClass
– CS1001 Lecture 30 – 12