0% found this document useful (0 votes)
12 views13 pages

Lecture 30

The document discusses exception handling in Python. It describes how to use try-except blocks to catch and handle exceptions at runtime. It provides examples of catching different exception types and raising new exceptions. It also discusses built-in exception classes in Python.

Uploaded by

Maxi Brad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views13 pages

Lecture 30

The document discusses exception handling in Python. It describes how to use try-except blocks to catch and handle exceptions at runtime. It provides examples of catching different exception types and raising new exceptions. It also discusses built-in exception classes in Python.

Uploaded by

Maxi Brad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Computer Science 1001

Lecture 30

Lecture Outline

• Exception handling

– CS1001 Lecture 30 –
Exception handling

• So far, when you run a program and an error occurs,


the program displays an error and aborts.

• We can do better than this with exception handling.

• An error that occurs at runtime is called an


exception.

• Exception handling enables a program to deal


with errors (exceptions) and continue its normal
execution.

• Basically the program can catch the exception and


then take steps to correct the error (if possible).

• For example, if the user enters a non-numeric input


when a number is required, the program could catch
the exception and prompt the user to enter a correct
input.

– CS1001 Lecture 30 – 1
try...except

• To handle exceptions we use the try...except


clause:

try:
<body>
except <ExceptionType>:
<handler>

• The <body> contains the code that may raise (or


throw) an exception.

• If an exception occurs, the rest of the code in


<body> is skipped.

• If the exception matches the ExceptionType, the


corresponding handler is executed.

• <handler> is the code that processes the exception.

• There are many different types of exceptions


(depending on the cause of the problem).

– 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.")

counts = 26 * [0] # Create and initialize counts


for line in infile:
# Invoke the countLetters function to count each letter
countLetters(line, counts)
infile.close() # Close file

# 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"))

# Count each letter in the string


def countLetters(line, counts):
line = line.lower()
for ch in line:
if ch.isalpha():
counts[ord(ch) - ord(’a’)] += 1

main() # Call the main function

– CS1001 Lecture 30 – 3
Example: FileNotFoundError

• In this example we first execute the statements to


input a filename and attempt to open a file with
that name.

• If an exception occurs during file opening (which


could be a FileNotFoundError), the code in the
except block (the handler) is executed.

• In this case the exception is handled by printing a


description of the problem, and we then iterate to
get another filename.

• If no exception occurs then the except block is


skipped.

• The while loop terminates once we have


successfully opened a file.

– CS1001 Lecture 30 – 4
Multiple exceptions

• If the exception type matches the exception name


after the except keyword, the except clause is
executed, and execution continues after the try
statement.

• If an exception occurs and it does not match the


exception name in the except clause, the exception
is passed on to the caller of this function.

• If no handler is found, execution stops and an


error message is displayed (this is an unhandled
exception).

• To handle more than one type of exception, a


try statement can have more than one except
clause, each of which will handle a different type of
exception.

• The try statement can also have an optional else


and/or a finally clause.

– CS1001 Lecture 30 – 5
Multiple exceptions

• In the most general form we have:

try:
<body>
except <ExceptionType1>:
<handler1>
...
except <ExceptionTypeN>:
<handlerN>
except:
<handlerExcept>
else:
<process_else>
finally:
<process_finally>

• The multiple excepts are similar to elifs.

• At most one except block (handler) will be


executed.

• When an exception occurs, the exception types in


the except clauses are checked sequentially to see
if they match the exception raised.

– CS1001 Lecture 30 – 6
Multiple exceptions

• If a match is found, the matching handler is executed


and the rest of the except clauses are skipped.

• Otherwise, the last except clause (without an


ExceptionType) is executed.

• An optional else clause is executed if no exception


is raised in the try body.

• An optional finally clause may be used to specify


cleanup actions that must always be performed.

• The finally clause is executed whether an


exception is raised or not.

• Note that exception handlers also handle exceptions


that may occur inside functions that are called from
the try body.

– CS1001 Lecture 30 – 7
Exception classes

• We have seen how to handle exceptions, but where


do they come from and how are they created?

• A exception is an instance of an exception class.

• There are many built-in exception classes.

• When a function detects an error, it creates an


object from an appropriate exception class and
throws the exception to the caller of the function.

• This is also called raising an exception.

– CS1001 Lecture 30 – 8
Exception classes
• Some of the built-in exception classes in Python:

BaseException

Exception

ArithmeticError LookupError SyntaxError

ZeroDivisionError IndentationError
IndexError
KeyError

• An except clause with an ExceptionType also


handles exception types that derive from that
exception class.

Details on built-in exceptions can be found at:


https://docs.python.org/3/library/exceptions.html#bltin-exceptions

– CS1001 Lecture 30 – 9
Example: division

• Consider the following code to output the result of


dividing two user-input values:

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:

Enter two numbers: 3 # TypeError


Something wrong in the input
The finally clause is executed

Enter two numbers: 2,3


The result is: 0.6666666666666666
No exceptions
The finally clause is executed

Enter two numbers: 2,0 # ZeroDivisionError


Division by zero!
The finally clause is executed

Enter two numbers: 0,3


The result is: 0.0
No exceptions
The finally clause is executed

Enter two numbers: a, b # NameError


Something wrong in the input
The finally clause is executed

Enter two numbers: 3 4 # SyntaxError


A comma may be missing in the input
The finally clause is executed

– CS1001 Lecture 30 – 11
Raising exceptions

• Suppose that we want to raise an exception in our


code.

• To do this, we would create an object from an


appropriate exception class and throw the exception
to the caller of the function, as in:

raise ExceptionClass("Something is wrong")

or
raise ExceptionClass

• In the second case, an instance will be created


by calling the exception class constructor with no
arguments.

• It is also possible to create our own exception


classes, which we should derive from the Exception
class (or one of its subclasses).

– CS1001 Lecture 30 – 12

You might also like