0% found this document useful (0 votes)
13 views20 pages

CS 109: Introduction To Computer Programming, Part B, Chapter 6 Zybooks

Chapter 6 zyBooks of CS 109: Introduction to Computer Programming, Part B. Authors and contributors Authors Bailey Miller / CSE Ph.D., Univ. of California, Riverside / zyBooks (Former software engineer at SpaceX) Senior Contributors Roman Lysecky / Professor of Electrical and Computer Engineering / Univ. of Arizona Frank Vahid / Professor of Computer Science and Engineering / Univ. of California, Riverside Nkenge Wheatland / Senior Content Developer / zyBooks Contributors Ron Siu / Content Deve

Uploaded by

clashernaut
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)
13 views20 pages

CS 109: Introduction To Computer Programming, Part B, Chapter 6 Zybooks

Chapter 6 zyBooks of CS 109: Introduction to Computer Programming, Part B. Authors and contributors Authors Bailey Miller / CSE Ph.D., Univ. of California, Riverside / zyBooks (Former software engineer at SpaceX) Senior Contributors Roman Lysecky / Professor of Electrical and Computer Engineering / Univ. of Arizona Frank Vahid / Professor of Computer Science and Engineering / Univ. of California, Riverside Nkenge Wheatland / Senior Content Developer / zyBooks Contributors Ron Siu / Content Deve

Uploaded by

clashernaut
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/ 20

11/10/25, 4:47 AM zyBooks

6.1 Handling exceptions using try and except


Error-checking code is code that a programmer introduces to detect and handle errors that occur while
the program executes. Python has special constructs known as exception-handling constructs because
they handle exceptional circumstances, or errors, during execution.
©zyBooks 11/10/25 04:47 2705711
Consider the following program in which a programmer enters weight and height.Jimmy Vo
The program then
GMUCS109KamranfarFall2025
outputs the corresponding body-mass index (BMI is one measure used to determine normal weight for a
given height).

Figure 6.1.1: BMI example without exception handling.

user_input = ""
while user_input != "q":
Enter weight (in pounds): 150
weight = int(input("Enter
Enter height (in inches): 66
weight (in pounds): "))
BMI: 24.207988980716255
height = int(input("Enter
(CDC: 18.6-24.9 normal)
height (in inches): "))
Enter any key ("q" to quit): a
bmi = (float(weight) /
Enter weight (in pounds): One-hundred fifty
float(height * height)) * 703
Traceback (most recent call last):
print(f"BMI: {bmi}")
File "test.py", line 3, in <module>
print("(CDC: 18.6-24.9
weight = int(input("Enter weight (in
normal)\n")
pounds): "))
# Source www.cdc.gov
ValueError: invalid literal for int() with
base 10: "One-hundred fifty"
user_input = input("Enter any
key ("q" to quit): ")

Above, the user entered a weight by writing out "One-hundred fifty" instead of giving a number such as
"150", which caused the int() function to produce an exception of type ValueError. The exception causes
the program to terminate.
A program should gracefully handle an exception and continue executing, instead of printing an error
message and stopping completely. Code that potentially may produce an exception is placed in a try
block. If the code in the try block causes an exception, then the code placed in a following except block is
©zyBooks 11/10/25 04:47 2705711
executed. Consider the program below, which modifies the BMI program to handle bad user input.
Jimmy Vo
GMUCS109KamranfarFall2025

Figure 6.1.2: BMI example with exception handling using try/except.

user_input = "" Enter weight (in pounds): 150


while user_input != "q": Enter height (in inches): 66
try: BMI: 24.207988980716255
(CDC: 18.6-24.9 normal)
https://learn.zybooks.com/zybook/GMUCS109KamranfarFall2025/chapter/6/print 1/20
11/10/25, 4:47 AM zyBooks
weight = int(input("Enter weight (in
pounds): ")) Enter any key ("q" to quit): a
height = int(input("Enter height (in Enter weight (in pounds): One-
inches): ")) hundred fifty
Could not calculate health info.
bmi = (float(weight) / float(height *
height)) * 703 Enter any key ("q" to quit): a
print(f"BMI: {bmi}") Enter weight (in pounds): 200
print("(CDC: 18.6-24.9 normal)\n") # Enter height (in inches): 62
Source www.cdc.gov ©zyBooks 11/10/25 04:47 2705711
BMI: 36.57648283038502
except: (CDC: 18.6-24.9Jimmy Vo
normal)
print("Could not calculate health GMUCS109KamranfarFall2025
info.\n") Enter any key ("q" to quit): q

user_input = input("Enter any key ("q" to


quit): ")

The try and except constructs are used together to implement exception handling, the process of
responding to unexpected or unwanted events and errors during execution (handling exceptional
conditions). A programmer could add additional code to do their own exception handling, such as
checking if every character in the user input string is a digit, but such code would make the original
program difficult to read.

Construct 6.1.1: Basic exception-handling constructs.

try:
# ... Normal code that might produce errors
except: # Go here if *any* error occurs in try block
# ... Exception handling code

PARTICIPATION
ACTIVITY 6.1.1: How try and except blocks handle exceptions.

Start 2x speed

try:
...
x = int("Ten") # Causes ValueError
...
... ©zyBooks 11/10/25 04:47 2705711
except: Jimmy Vo
# Handle exception, e.g., print messageGMUCS109KamranfarFall2025

...

Error message...

https://learn.zybooks.com/zybook/GMUCS109KamranfarFall2025/chapter/6/print 2/20
11/10/25, 4:47 AM zyBooks

Captions keyboard_arrow_down
When a try is reached, the statements in the try block are executed. If no exception occurs, the except
block is skipped and the program continues. If an exception does occur, the except block is executed, and
©zyBooks 11/10/25 04:47 2705711
the program continues after the except block. Any statements in the try block notJimmy
executed
Vo before the
exception occurred are skipped. GMUCS109KamranfarFall2025

PARTICIPATION
ACTIVITY
6.1.2: Exception basics.

1) Execution jumps to an except block only


if an error occurs in the preceding try
block.
True
False

2) After an error occurs in a try block, and


the following except block has executed,
execution resumes after the error in the
try block.
True
False

Table 6.1.1: Common exception types.

Type Reason exception is raised

EOFError input() hits an end-of-file condition (EOF) without reading any input.

KeyError A dictionary key is not found in the set of keys.


©zyBooks 11/10/25 04:47 2705711
ZeroDivisionError Divide by zero error Jimmy Vo
GMUCS109KamranfarFall2025
ValueError Invalid value (Ex: Input mismatch)

IndexError Index is out of bounds.

Source: Python: Built-in Exceptions

https://learn.zybooks.com/zybook/GMUCS109KamranfarFall2025/chapter/6/print 3/20
11/10/25, 4:47 AM zyBooks
CHALLENGE
ACTIVITY
6.1.1: Handling exceptions using try and except.

678064.5411422.qx3zqy7

Start

Type the program's output


©zyBooks 11/10/25 04:47 2705711
Jimmy Vo
try: Input GMUCS109KamranfarFall2025
number1 = int(input()) 5
print(number1 * 4)
H
number2 = int(input())
print(number2 * 4) Output
except:
print("x")
print("e")

1 2 3 4

Check Next

CHALLENGE
ACTIVITY
6.1.2: Handling exceptions.

678064.5411422.qx3zqy7

Start

Add a try block that:

Reads integer num_cents from input.

Outputs the value of num_cents followed by:

" cents = "


the value of num_cents divided by 10 as an integer
" dimes"

Click here for example 1 (valid input) keyboard_arrow_down ©zyBooks 11/10/25 04:47 2705711
Jimmy Vo

keyboard_arrow_down
GMUCS109KamranfarFall2025
Click here for example 2 (invalid input)

Note: num_cents // 10 returns the value of num_cents divided by 10 as an integer.

1
2 # Your code goes here
3
4 except:
https://learn.zybooks.com/zybook/GMUCS109KamranfarFall2025/chapter/6/print 4/20
11/10/25, 4:47 AM zyBooks
4 except:
5 print("Error: The number of cents entered is invalid")

©zyBooks 11/10/25 04:47 2705711


Jimmy Vo
GMUCS109KamranfarFall2025

1 2 3

Check Next level

6.2 Multiple exception handlers


Sometimes the code in a try block may generate different types of exceptions. In the previous BMI
example, a ValueError was generated when the int() function passed a string argument that contained
letters. Other types of errors (such as NameError, TypeError, etc.) might also be generated, and thus a
program may need to have unique exception-handling code for each error type. Multiple exception
handlers can be added to a try block by adding additional except blocks and specifying the type of
exception that each except block handles.

Construct 6.2.1: Multiple except blocks.

try:
# ... Normal code
except exceptiontype1:
# ... Code to handle exceptiontype1
except exceptiontype2:
# ... Code to handle exceptiontype2 ©zyBooks 11/10/25 04:47 2705711
... Jimmy Vo
except: GMUCS109KamranfarFall2025
# ... Code to handle other exception types

PARTICIPATION
ACTIVITY 6.2.1: Multiple exception handlers.

https://learn.zybooks.com/zybook/GMUCS109KamranfarFall2025/chapter/6/print 5/20
11/10/25, 4:47 AM zyBooks

Start 2x speed
try:
# ... # No error
# ... # Causes TypeError
# ...
except ValueError:
# Handle exception, e.g., print message 1
except TypeError:
# Handle exception, e.g., print message 2
except:
# Handle any other exception type ©zyBooks 11/10/25 04:47 2705711
Jimmy Vo
# ... Resume normal code below except GMUCS109KamranfarFall2025
Error message 2...

Captions keyboard_arrow_down
An except block with no type (as in the above BMI example) handles any unspecified exception type,
acting as a catchall for all other exception types. Good practice is to generally avoid the use of a catchall
except clause. A programmer should instead specify the particular exceptions to be handled. Otherwise, a
program bug might be hidden when the catchall except clause handles an unexpected type of error.

If no exception handler exists for an error type, then an unhandled exception may occur. An unhandled
exception causes the interpreter to print the exception that occurred and halt.

The following program introduces a second exception handler to the BMI program, handling a case where
the user enters "0" as the height, which would cause a ZeroDivisionError exception to occur when
calculating the BMI.

Figure 6.2.1: BMI example with multiple exception types.

user_input = "" Enter weight (in pounds): 150


while user_input != "q": Enter height (in inches): 66
try: BMI: 24.207988980716255
©zyBooks 11/10/25 04:47 2705711
weight = int(input("Enter weight (in (CDC: 18.6-24.9 normal)
Jimmy Vo
pounds): "))
GMUCS109KamranfarFall2025
height = int(input("Enter height (in Enter any key ("q" to quit): a
inches): ")) Enter weight (in pounds): One-
hundred fifty
bmi = (float(weight) / float(height * Could not calculate health info.
height)) * 703
print(f"BMI: {bmi}") Enter any key ("q" to quit): a
print("(CDC: 18.6-24.9 normal)\n") # Enter weight (in pounds): 150
Source www.cdc.gov Enter height (in inches): 0
except ValueError: Invalid height entered. Must be >
https://learn.zybooks.com/zybook/GMUCS109KamranfarFall2025/chapter/6/print 6/20
11/10/25, 4:47 AM zyBooks
print("Could not calculate health 0.
info.\n") Enter any key ("q" to quit): q
except ZeroDivisionError:
print("Invalid height entered. Must
be > 0.")

user_input = input('Enter any key ("q" to


quit): ')

©zyBooks 11/10/25 04:47 2705711


Jimmy Vo
GMUCS109KamranfarFall2025
In some cases, multiple exception types should be handled by the same exception handler. A tuple can be
used to specify all of the exception types for which a handler's code should be executed.

Figure 6.2.2: Multiple exception types in a single exception handler.

try:
# ...
except (ValueError, TypeError):
# Exception handler for any ValueError or TypeError that occurs.
except (NameError, AttributeError):
# A different handler for NameError and AttributeError exceptions.
except:
# A different handler for any other exception type.

PARTICIPATION
ACTIVITY
6.2.2: Multiple exceptions.

1) Fill in the missing code so that any type


of error in the try block is handled.
ages = []
prompt = "Enter age ("q" to quit): "
user_input = input(prompt)
while user_input != "q":
try:

ages.append(int(user_input))
user_input =
input(prompt)

print("Unable to add ©zyBooks 11/10/25 04:47 2705711


age.") Jimmy Vo
user_input = GMUCS109KamranfarFall2025
input(prompt)
print(ages)

Check Show answer

https://learn.zybooks.com/zybook/GMUCS109KamranfarFall2025/chapter/6/print 7/20
11/10/25, 4:47 AM zyBooks

2) An AttributeError occurs if a function


does not exist in an imported module.
Fill in the missing code to handle
AttributeErrors gracefully and generate
an error if other types of exceptions
occur.
import my_lib ©zyBooks 11/10/25 04:47 2705711
try: Jimmy Vo
result = my_lib.magic() GMUCS109KamranfarFall2025

print("No magic() function in


my_lib.")

Check Show answer

3) If a file cannot be opened, then an


IOError may occur. Fill in the missing
code so that the program specially
handles AttributeErrors and IOErrors,
and also doesn't crash for any other
type of error.
import my_lib
try:
result = my_lib.magic()
f = open(result, "r")
print f.read()

print("Could not open file.")


except AttributeError:
print("No magic() function in
my_lib")
except:
print("Something bad has
happened.")

Check Show answer

CHALLENGE
ACTIVITY 6.2.1: Enter the output of multiple exception handlers. ©zyBooks 11/10/25 04:47 2705711
Jimmy Vo
GMUCS109KamranfarFall2025
678064.5411422.qx3zqy7

Start

Type the program's output

https://learn.zybooks.com/zybook/GMUCS109KamranfarFall2025/chapter/6/print 8/20
11/10/25, 4:47 AM zyBooks

user_input = input() Input


while user_input != "end": six
try:
# Possible ValueError 4
divisor = int(user_input) 1
# Possible ZeroDivisionError 0
print(60 // divisor) # Truncates to an integer
except ValueError: end
print("v") ©zyBooks 11/10/25 04:47 2705711
except ZeroDivisionError: Output Jimmy Vo
print("z") GMUCS109KamranfarFall2025
user_input = input()
print("OK")

1 2 3

Check Next

CHALLENGE
ACTIVITY
6.2.2: Handling exceptions with math operations and common data types.

678064.5411422.qx3zqy7

Start

Complete the following tasks:

Write an exception handler to catch ValueError and output


"math.sqrt(): Area cannot be negative."
Write an exception handler to catch ZeroDivisionError and output
"Rain per square meter = Rainfall / Area: Area cannot be zero."

Click here to show example keyboard_arrow_down


1 import math
2
3 try:
4 square_area = float(input())
5 total_rainfall = 50.0
6 print(f"Side of the square area: {math.sqrt(square_area)}")
7 print(f"Rain per square meter: {total_rainfall / ©zyBooks
square_area}")
11/10/25 04:47 2705711
8 Jimmy Vo
9 # Your code goes here GMUCS109KamranfarFall2025
10

https://learn.zybooks.com/zybook/GMUCS109KamranfarFall2025/chapter/6/print 9/20
11/10/25, 4:47 AM zyBooks

1 2

Check Next level

©zyBooks 11/10/25 04:47 2705711


Jimmy Vo
Exploring further: GMUCS109KamranfarFall2025

Python built-in exception types

6.3 Raising exceptions


Consider the BMI example once again, in which a user enters a weight and height, and that outputs the
corresponding body-mass index. The programmer may wish to ensure that a user enters only valid heights
and weights (ex.: greater than 0). Thus, the programmer must introduce error-checking code.

A naive approach to adding error-checking code is to intersperse if-else statements throughout the normal
code. Of particular concern is the highlighted code, which is new branching logic added to the normal
code, making the normal code flow of "get weight, get height, then print BMI" harder to see. Furthermore,
the second check for negative values before printing the BMI is redundant and prone to a programming
error caused by inconsistency with the earlier checks (e.g., checking for <= here rather than just <).

Figure 6.3.1: BMI example with error-checking code but without using exception-
handling constructs.

user_input = ""
while user_input != "q":
weight = int(input("Enter weight (in pounds): "))
if weight < 0:
print("Invalid weight.")
else:
height = int(input("Enter height (in inches): "))
©zyBooks 11/10/25 04:47 2705711
if height <= 0: Jimmy Vo
print("Invalid height") GMUCS109KamranfarFall2025

if (weight < 0) or (height <= 0):


print("Cannot compute info.")
else:
bmi = (float(weight) / float(height * height)) * 703
print(f"BMI: {bmi}")
print("(CDC: 18.6-24.9 normal)\n") # Source www.cdc.gov

https://learn.zybooks.com/zybook/GMUCS109KamranfarFall2025/chapter/6/print 10/20
11/10/25, 4:47 AM zyBooks

user_input = input('Enter any key ("q" to quit): ')

The following program shows the same error checking carried out using exception-handling constructs.
The normal code is enclosed in a try block. Code that detects an error can execute a raise statement,
which causes immediate exit from the try block and the execution of an exception handler. The exception
©zyBooks
handler prints the argument passed by the raise statement that brought 11/10/25
execution. 04:47
Notice that2705711
the normal
Jimmy Vo
code flow is not obscured by new if-else statements. You can clearly see that the flow is "get weight, get
GMUCS109KamranfarFall2025
height, then print BMI".

Figure 6.3.2: BMI example with error-checking code that raises exceptions.

user_input = ""
Enter weight (in pounds):
while user_input != "q":
166
try:
Enter height (in inches): 55
weight = int(input("Enter weight (in
BMI: 38.57785123966942
pounds): "))
(CDC: 18.6-24.9 normal)
if weight < 0:
raise ValueError("Invalid weight.")
Enter any key ("q" to quit):
a
height = int(input("Enter height (in
Enter weight (in pounds):
inches): "))
180
if height <= 0:
Enter height (in inches): -5
raise ValueError("Invalid height.")
Invalid height.
Could not calculate health
bmi = (float(weight) * 703) / (float(height
info.
* height))
print(f"BMI: {bmi}")
Enter any key ("q" to quit):
print("(CDC: 18.6-24.9 normal)\n")
a
# Source www.cdc.gov
Enter weight (in pounds): -2
Invalid weight.
except ValueError as excpt:
Could not calculate health
print(excpt)
info.
print("Could not calculate health info.\n")
Enter any key ("q" to quit):
user_input = input('Enter any key ("q" to
q
quit): ')

A statement like raise ValueError("Invalid weight.") creates a new11/10/25


©zyBooks exception of type
04:47 2705711
Jimmy Vo
ValueError with a string argument that details the issue. The programmer could have specified any type of
GMUCS109KamranfarFall2025
exception in place of ValueError, such as NameError or TypeError, but ValueError most closely describes
the exception being handled in this case. The as keyword binds a name to the exception being handled.
The statement except ValueError as excpt creates a new variable, excpt, that the exception-
handling code might inspect for details about the exception instance. Printing the variable excpt prints the
string argument passed to the exception when raised.

https://learn.zybooks.com/zybook/GMUCS109KamranfarFall2025/chapter/6/print 11/20
11/10/25, 4:47 AM zyBooks
PARTICIPATION 6.3.1: Exceptions.
ACTIVITY

How to use this tool keyboard_arrow_down


except NameError: except: try except (ValueError, NameError):

©zyBooks 11/10/25 04:47 2705711


raise ValueError Jimmy Vo
GMUCS109KamranfarFall2025

Describes a block of code that uses


exception handling

An exception handler for NameError


exceptions

An exception handler for ValueError


and NameError exceptions

A catchall exception handler

Causes a ValueError exception to


occur

Reset

CHALLENGE
ACTIVITY
6.3.1: Exception handling.

678064.5411422.qx3zqy7

Start

Type the program's output

try: Input
user_age = int(input()) ©zyBooks 11/10/25 04:47 2705711
50
Jimmy Vo
if user_age < 0: GMUCS109KamranfarFall2025
raise ValueError("Invalid age") Output
# Source: https://www.heart.org/en/healthy-living/fitness
avg_max_heart_rate = 220 - user_age

print(f"Avg: {avg_max_heart_rate}")

https://learn.zybooks.com/zybook/GMUCS109KamranfarFall2025/chapter/6/print 12/20
11/10/25, 4:47 AM zyBooks
except ValueError as excpt:
print(f"Error: {excpt}")

1 2 3 4

Check Next

©zyBooks 11/10/25 04:47 2705711


CHALLENGE
6.3.2: Raising exceptions. Jimmy Vo
ACTIVITY
GMUCS109KamranfarFall2025

678064.5411422.qx3zqy7

Start

Integers seats_per_row and num_rows are read from input, representing the number of seats per
row and number of rows of seats in a classroom. In the try block:

Raise a ValueError exception with the message "Number of seats per row must be positive"
if seats_per_row is less than or equal to 0.
Raise a ValueError exception with the message "Number of rows of seats must be positive"
if num_rows is less than or equal to 0.

Click here for example 1 (invalid input - negative number of seats per row) keyboard_arrow_down
Click here for example 2 (invalid input - negative number of rows of seats) keyboard_arrow_down
Click here for example 3 (valid input) keyboard_arrow_down
1 try:
2 seats_per_row = int(input())
3 num_rows = int(input())
4
5 """ Your code goes here """
6
7 total_seats = seats_per_row * num_rows
8
9 print(f"Number of seats in the classroom: {total_seats}")
10
11 except ValueError as excpt:
12 print(f"Error: {excpt}") ©zyBooks 11/10/25 04:47 2705711
Jimmy Vo
GMUCS109KamranfarFall2025

1 2

https://learn.zybooks.com/zybook/GMUCS109KamranfarFall2025/chapter/6/print 13/20
11/10/25, 4:47 AM zyBooks

Check Next level

6.4 Exceptions with functions


©zyBooks 11/10/25 04:47 2705711
Jimmy Vo
The power of exceptions becomes even more clear when used within functions. If an exception is raised
GMUCS109KamranfarFall2025
within a function and is not handled within that function, then the function is immediately exited and the
calling function is checked for a handler, and so on up the function call hierarchy. The following program
illustrates this. Note the clarity of the normal code, which obviously "gets the weight, gets the height, and
prints the BMI" – the error checking code does not obscure the normal code.

Figure 6.4.1: BMI example using exception-handling constructs along with


functions.

def get_weight():
weight = int(input("Enter weight (in pounds):
"))
if weight < 0:
raise ValueError("Invalid weight.")
Enter weight (in pounds):
return weight
150
Enter height (in inches): 66
def get_height():
BMI: 24.207988980716255
height = int(input("Enter height (in inches):
(CDC: 18.6-24.9 normal)
"))
if height <= 0:
Enter any key ("q" to quit):
raise ValueError("Invalid height.")
a
return height
Enter weight (in pounds): -1
Invalid weight.
user_input = ""
Could not calculate health
while user_input != "q":
info.
try:
weight = get_weight()
Enter any key ("q" to quit):
height = get_height()
a
Enter weight (in pounds):
bmi = (float(weight) / float(height *
150
height)) * 703
Enter height (in inches): -1
print(f"BMI: {bmi}")
Invalid height.
print("(CDC: 18.6-24.9 normal)\n") ©zyBooks 11/10/25 04:47 2705711
Could not calculate
Jimmy Vo health
# Source www.cdc.gov
info.
GMUCS109KamranfarFall2025
except ValueError as excpt:
Enter any key ("q" to quit):
print(excpt)
q
print("Could not calculate health
info.\n")

user_input = input('Enter any key ("q" to


quit): ')

https://learn.zybooks.com/zybook/GMUCS109KamranfarFall2025/chapter/6/print 14/20
11/10/25, 4:47 AM zyBooks

Suppose get_weight() raises an exception of type ValueError. The get_weight() function does not handle
exceptions (there is no try block in the function), so it immediately exits. Going up the function call
hierarchy returns execution to the global scope script code, where the call to get_weight() was in a try
block, so the exception handler for ValueError is executed.
Notice the clarity of the script's code. Without exceptions, the get_weight() function would have had to
indicate failure, perhaps through a special return value like -1. The script would 11/10/25
©zyBooks have had04:47
to check for such
2705711
Jimmy Vo
failure and would have required additional if-else statements, obscuring the functionality of the code.
GMUCS109KamranfarFall2025

PARTICIPATION
ACTIVITY 6.4.1: Exceptions in functions.

1) For a function that may contain a raise


statement, the function's statements
must be placed in a try block within the
function.
True
False

2) A raise statement executed in a function


automatically causes a jump to the last
return statement in the function.
True
False

3) A key goal of exception handling is to


avoid polluting normal code with
distracting error-handling code.
True
False

CHALLENGE
ACTIVITY
6.4.1: Moving on a chess board. fullscreen Full screen

678064.5411422.qx3zqy7
©zyBooks 11/10/25 04:47 2705711
Jimmy Vo
Organize the code blocks so that: GMUCS109KamranfarFall2025

get_column() throws a ValueError if column is not between "a" and "h", both inclusive.
get_row() throws a ValueError if row is not between 1 and 8, both inclusive.
the try block gets the values of column and row and outputs the move.
the except block outputs the argument passed by a raise statement.

https://learn.zybooks.com/zybook/GMUCS109KamranfarFall2025/chapter/6/print 15/20
11/10/25, 4:47 AM zyBooks

Click here for example keyboard_arrow_down


How to use this tool keyboard_arrow_down
Unused
if (row < 1) or (row > 8):
raise ValueError("Row must be between 1 and 8")
©zyBooks 11/10/25 04:47 2705711
try: Jimmy Vo
GMUCS109KamranfarFall2025
except ValueError as excpt:
print(excpt)

column = get_column()
row = get_row()

print(f"Move to square {column}{row}")

if (column < "a") or (column > "h"):


raise ValueError("Column must be between a and h")

main.py Load default template...

def get_column():
column = input()

return column

def get_row():
row = int(input())

return row

©zyBooks 11/10/25 04:47 2705711


Jimmy Vo
GMUCS109KamranfarFall2025

Check

https://learn.zybooks.com/zybook/GMUCS109KamranfarFall2025/chapter/6/print 16/20
11/10/25, 4:47 AM zyBooks

6.5 Using finally to clean up


A programmer wants to execute code regardless of whether or not an exception has been raised in a try
block. Ex: If an exception occurs while reading data from a file, the file should still be closed using the
file.close() method, no matter if an exception interrupted the read operation. The finally clause of a try
statement allows a programmer to specify clean-up actions that are always executed. The following
©zyBooks 11/10/25 04:47 2705711
illustration demonstrates. Jimmy Vo
GMUCS109KamranfarFall2025
PARTICIPATION
ACTIVITY
6.5.1: Clean-up actions in a finally clause are always executed.

Start 2x speed

try: try:
# ... # No exception occurs # ... # exception occurs
except: except:
# Handle exception # Handle exception
finally: finally:
# Clean up actions always executed # Clean up actions always executed

In finally block... Exception message...


In finally block...

Captions keyboard_arrow_down
The finally clause is always the last code executed before the try block finishes.

If no exception occurs, then execution continues in the finally clause and proceeds with the program.
If a handled exception occurs, an exception handler executes and then the finally clause.
If an unhandled exception occurs, then the finally clause executes and the exception is re-raised.
©zyBooks 11/10/25 04:47 2705711
The finally clause also executes if any break, continue, or return statement causes the try block to be
Jimmy Vo
exited. GMUCS109KamranfarFall2025

The finally clause can be combined with exception handlers, provided that the finally clause comes last.
The following program attempts to read integers from a file. The finally clause is always executed, even if
an exception occurs when reading the data (such as if the file contains letters, thus causing int() to raise
an exception, or if the file does not exist).

https://learn.zybooks.com/zybook/GMUCS109KamranfarFall2025/chapter/6/print 17/20
11/10/25, 4:47 AM zyBooks

Figure 6.5.1: Clean-up actions using finally.

nums = []
rd_nums = -1
my_file = input("Enter file name: ") Enter file name: myfile.txt
Opening myfile.txt
try: Closing myfile.txt
print("Opening", my_file) ©zyBooks
Numbers 11/10/25
found: 5 04:47 2705711
423 234
rd_nums = open(my_file, "r") # Might cause ... Jimmy Vo
IOError GMUCS109KamranfarFall2025
Enter file name: myfile.txt
Opening myfile.txt
for line in rd_nums: Could not read number from
nums.append(int(line)) # Might cause myfile.txt
ValueError Closing myfile.txt
except IOError: Numbers found:
print(f"Could not find {my_file}") ...
except ValueError: Enter file name:
print(f"Could not read number from invalidfile.txt
{my_file}") Opening invalidfile.txt
finally: Could not find
print(f"Closing {my_file}") invalidfile.txt
if rd_nums != -1: Closing invalidfile.txt
rd_nums.close() Numbers found:
print(f'Numbers found: {" ".join([str(n) for
n in nums])}')

PARTICIPATION
ACTIVITY
6.5.2: Finally.

Assume that the following function has been defined.

def divide(a, b):


z = -1
try:
z = a / b
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print(f"Result is {z}")
1) What is the output of divide(4, 2)?
Cannot divide by zero.
©zyBooks 11/10/25 04:47 2705711
Result is -1. Jimmy Vo
GMUCS109KamranfarFall2025
Cannot divide by zero.
Result is 2.0.
Result is 2.0.

https://learn.zybooks.com/zybook/GMUCS109KamranfarFall2025/chapter/6/print 18/20
11/10/25, 4:47 AM zyBooks

2) What is the output of divide(4, 0)?


Cannot divide by zero.
Result is -1.
Cannot divide by zero.
Result is 2.0.
Result is 0.0. ©zyBooks 11/10/25 04:47 2705711
Jimmy Vo
CHALLENGE GMUCS109KamranfarFall2025
ACTIVITY 6.5.1: Using finally to wrap up before returning a value. fullscreen Full screen

678064.5411422.qx3zqy7
Organize the try, except, and finally blocks so that "Wrap up and return" is output before pick()
returns any value.

Click here for examples keyboard_arrow_down


How to use this tool keyboard_arrow_down
Unused

except:
return "Index out of range"

finally:

print("Wrap up and return")

try:
index = int(input())

print("Item is", items[index])

if index == 0:
return "Integer"
elif index == 1:
return "Float"
else:
return "String"

©zyBooks 11/10/25 04:47 2705711


main.py LoadJimmy Votemplate...
default
GMUCS109KamranfarFall2025
def pick():
items = [7, 2.5, "egg"] # Valid indices: -3 to 2

# Organize the try, except, and finally blocks in pick()

result = pick()

https://learn.zybooks.com/zybook/GMUCS109KamranfarFall2025/chapter/6/print 19/20
11/10/25, 4:47 AM zyBooks
print(result)

©zyBooks 11/10/25 04:47 2705711


Jimmy Vo
GMUCS109KamranfarFall2025

Check

©zyBooks 11/10/25 04:47 2705711


Jimmy Vo
GMUCS109KamranfarFall2025

https://learn.zybooks.com/zybook/GMUCS109KamranfarFall2025/chapter/6/print 20/20

You might also like