You are on page 1of 6

USAMA MEHBOOB ROLL NO 2022F-SE-225

SECTION E
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:
instagram = [{'Photos': 6, 'disLikes': 22, 'Comments': 3},
{'disLikes': 13, 'Comments': 1, 'Shares': 6}, {'Photos': 6,

'disLikes': 33, 'Comments': 9, 'Shares': 4}, {'Comments':


5,'Shares': 1}, {'Photos': 5, 'Comments': 4, 'Shares': 2},
{'Photos': 3, 'disLikes': 19, 'Comments': 3}] total_dislikes
= 0
for post in instagram:
total_dislikes = total_dislikes + post['disLikes']

Errors:
1. If a post in the Instagram data doesn’t contain the key ‘disLikes’,it will raise a key error.
2. To fix the error, we can use the try-except block to handle the Key error.

Correct code:

Output:

1|Page
USAMA MEHBOOB ROLL NO 2022F-SE-225
SECTION E
2. Code:
def Interest(cost, month, rate):
if rate > 100:
raise ValueError(rate)
interest1 = (cost * month * rate) / 100
print('The Interest is', interest1)
return interest1
print('Case 1')
Interest(650, 2, 6)
print('Case 2')
Interest(880, 2, 900)

Errors:
1. The raise Value error (rate) statement a value error with the value rate passed as an

argument. But the error message should be more informative and indicate that the value

passed is valid.

Correct code:

Output:

2|Page
USAMA MEHBOOB ROLL NO 2022F-SE-225
SECTION E
3. Code:
my_list = [3,7, 9, 4, 6]

print(my_list[6])

Errors:
1. The index of the list is out of range, the index you provided is 6 but the list only have 5
elements.
2. The try-except block is used to catch the IndexError that is raised when trying to access
an index that is out of range..

Correct code:

Output:

B. What will be the output of the following programs:

1. Code:

Output:

3|Page
USAMA MEHBOOB ROLL NO 2022F-SE-225
SECTION E
2. Code:

Output:

3.Code:

Output:

4|Page
USAMA MEHBOOB ROLL NO 2022F-SE-225
SECTION E
C. Write Python programs for the following:
Program no: 1
Task 01:
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

Output

5|Page
USAMA MEHBOOB ROLL NO 2022F-SE-225
SECTION E

Program no: 2
Task 02:
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:

Output:

6|Page

You might also like