Lecture 21
Lecture 21
Chapter 11:
Exceptions
1
Exceptions
• An exception is a runtime error that
occurs while a program is executing.
• In Python, exceptions are raised when
an invalid operation is performed.
• When a Python script raises an
exception, it must either handle the
exception immediately otherwise it
terminates and quits.
• Example: try an input ‘one hundred fifty’
for this code:
Handling exceptions
• Python has special constructs known as exception-handling constructs
• Because they handle exceptional circumstances, or errors, during execution
Example:
Handling
exceptions: _________________ FIXME ____________________________
using try and
my_list = [1, 2, 3]
except try:
print(my_list[3])
except:
print("Enter another index")
_____________________________________________________
Output: Enter another index
What is multiple exception
handlers and why we need that?
• An except block with no type (as previous examples) handles any unspecified
exception type, acting as a catchall for all other exception types
• 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.
user_input = ''
while user_input != 'q':
try:
weight = int(input("Enter weight (in pounds):
"))
height = int(input("Enter height (in inches):
"))
Example: bmi = (float(weight) / float(height * height)) *
Multiple 703
print(f'BMI: {bmi}')
exception print('(CDC: 18.6-24.9 normal)\n')
handlers except ValueError:
print('Could not calculate health info.\n')
• Write a program that prompts the user to enter a list of numbers (separated by space), calculates the
average of the numbers, and displays the result.
• However, if the list is empty, the program should display an error message and prompt the user to try
again. If the list contains a non-numeric element, the program should display an error message and
prompt the user to try again
• Input example:
• 5678
• Output:
• 6.5
Solution
try:
list_num = input("Enter a list of numbers separated by spaces:
").split()
num_list = [int(num) for num in list_num]
summation = sum(num_list)
average = summation/len(num_list)
print(average)
except ValueError:
print("Invalid input")
except ZeroDivisionError:
print("List cannot be empty")
Solution
try:
list_num = input("Enter a list of numbers separated by spaces:
").split()
num_list = [int(num) for num in list_num]
summation = sum(num_list)
average = summation/len(num_list)
print(summation)
print(average)
except (ValueError, ZeroDivisionError):
print("Invalid input or empty list")