Lab 13
Lab 13
LAB # 13
EXCEPTION HANDLING
OBJECTIVE
Constructing a fault tolerant program by implementing exception handling techniques.
EXERCISE:
A. Point out the errors, if any, and paste the output also in the following Python programs.
1. Code:
2. Code:
2023F-BSE-088
Programming Fundamentals (SWE-102) SSUET/QR/114
3. Code:
my_list = [3,7, 9, 4, 6]
print(my_list[6])
Correct Code: Output:
my_list = [3, 7, 9, 4, 6]
try:
print(my_list[6])
except IndexError as e:
print(f"Error: {e}")
last_element = my_list[-1]
print("Last Element:", last_element)
2023F-BSE-088
Programming Fundamentals (SWE-102) SSUET/QR/114
1. Code: Output:
a = 'Hello World!'
try:
a + 10
except BaseException as error:
print('Exception occurred: {}'.format(error))
lst = [5, 10, 20]
2. Code: Output:
3. Code:
import sys
List_random = ['a', 0, 2]
for enter in List_random:
try:
print("The entry is", enter)
r = 1 / int(enter)
break
except:
print("Oops!", sys.exc_info()[0], "occurred.")
print("Next entry.")
print()
print("The reciprocal of", enter, "is", r)
Output
2023F-BSE-088
Programming Fundamentals (SWE-102) SSUET/QR/114
1. Write a program to make a basic calculator for kids in super market so that they may
verify their calculation using Exceptional Handling. This program must have all four
arithmetic operations.
Code:
2023F-BSE-088
Programming Fundamentals (SWE-102) SSUET/QR/114
2. Write a program to store 5 types of coffee with a number (e.g. Espresso=1, Cappuccino=2,
Macchiato=3 etc.), Now ask the user “which coffee you would like to have, please enter
your desire number”. Use try block to print the coffee name, except block to display if
any invalid number or character has been entered by the user and final block to greet
the customer at last.
Code:
def coffee_menu():
print("Coffee Menu:")
print("1. Espresso")
print("2. Cappuccino")
print("3. Macchiato")
print("4. Latte")
print("5. Americano")
def greet_customer():
print("Thank you for choosing our coffee shop! Enjoy your coffee!")
try:
coffee_menu()
coffee_number = int(input("Enter the number of the coffee you would like to have: "))
coffee_names = {
1: "Espresso",
2: "Cappuccino",
3: "Macchiato",
4: "Latte",
5: "Americano"
}
selected_coffee = coffee_names[coffee_number]
print(f"You selected: {selected_coffee}")
except ValueError:
print("Invalid input. Please enter a number.")
except KeyError:
print("Invalid coffee number. Please select a valid number from the menu.")
finally:
greet_customer()
Output
2023F-BSE-088
Programming Fundamentals (SWE-102) SSUET/QR/114
2023F-BSE-088