0% found this document useful (0 votes)
7 views17 pages

Lecture 21

Uploaded by

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

Lecture 21

Uploaded by

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

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

• A program should gracefully handle an exception and continue


executing, instead of printing an error message and stopping
completely.
Handling exceptions: using try
and except
• 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 the program continues
after the except block.
• The try and except
constructs are used
together to implement
exception handling:
Handling exceptions: using try
and except
Modifying the BMI program to handle invalid user input:
• 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
executed.
Common exception types
Example:
Handling
exceptions:
using try and
except
Example:
Handling
exceptions:
using try and
except
my_list = [1, 2, 3]
print(my_list[3])

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 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.
Multiple exception handlers

• 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')

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


user_input = ''
while user_input != 'q':
try:
weight = int(input("Enter weight (in pounds): "))
height = int(input("Enter height (in inches): "))

bmi = (float(weight) / float(height * height)) * 703


Example: print(f'BMI: {bmi}')
Multiple print('(CDC: 18.6-24.9 normal)\n')
www.cdc.gov
# Source

exception except ValueError:


handlers print('Could not calculate health info.\n')
except ZeroDivisionError:
print('Invalid height entered. Must be > 0.')

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


_______________________________________________________________
____
Input: zero
Output: Invalid height entered. Must be > 0.
Multiple exception handlers
Problem

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

You might also like