CS 109: Introduction To Computer Programming, Part B, Chapter 6 Zybooks
CS 109: Introduction To Computer Programming, Part B, Chapter 6 Zybooks
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
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.
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.
EOFError input() hits an end-of-file condition (EOF) without reading any input.
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
1 2 3 4
Check Next
CHALLENGE
ACTIVITY
6.1.2: Handling exceptions.
678064.5411422.qx3zqy7
Start
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)
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")
1 2 3
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.
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.
ages.append(int(user_input))
user_input =
input(prompt)
https://learn.zybooks.com/zybook/GMUCS109KamranfarFall2025/chapter/6/print 7/20
11/10/25, 4:47 AM zyBooks
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
https://learn.zybooks.com/zybook/GMUCS109KamranfarFall2025/chapter/6/print 8/20
11/10/25, 4:47 AM zyBooks
1 2 3
Check Next
CHALLENGE
ACTIVITY
6.2.2: Handling exceptions with math operations and common data types.
678064.5411422.qx3zqy7
Start
https://learn.zybooks.com/zybook/GMUCS109KamranfarFall2025/chapter/6/print 9/20
11/10/25, 4:47 AM zyBooks
1 2
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
https://learn.zybooks.com/zybook/GMUCS109KamranfarFall2025/chapter/6/print 10/20
11/10/25, 4:47 AM zyBooks
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): ')
https://learn.zybooks.com/zybook/GMUCS109KamranfarFall2025/chapter/6/print 11/20
11/10/25, 4:47 AM zyBooks
PARTICIPATION 6.3.1: Exceptions.
ACTIVITY
Reset
CHALLENGE
ACTIVITY
6.3.1: Exception handling.
678064.5411422.qx3zqy7
Start
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
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
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")
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.
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
column = get_column()
row = get_row()
def get_column():
column = input()
return column
def get_row():
row = int(input())
return row
Check
https://learn.zybooks.com/zybook/GMUCS109KamranfarFall2025/chapter/6/print 16/20
11/10/25, 4:47 AM zyBooks
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
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
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.
https://learn.zybooks.com/zybook/GMUCS109KamranfarFall2025/chapter/6/print 18/20
11/10/25, 4:47 AM zyBooks
678064.5411422.qx3zqy7
Organize the try, except, and finally blocks so that "Wrap up and return" is output before pick()
returns any value.
except:
return "Index out of range"
finally:
try:
index = int(input())
if index == 0:
return "Integer"
elif index == 1:
return "Float"
else:
return "String"
result = pick()
https://learn.zybooks.com/zybook/GMUCS109KamranfarFall2025/chapter/6/print 19/20
11/10/25, 4:47 AM zyBooks
print(result)
Check
https://learn.zybooks.com/zybook/GMUCS109KamranfarFall2025/chapter/6/print 20/20