-
Notifications
You must be signed in to change notification settings - Fork 6
/
exception handling.py
151 lines (116 loc) · 2.71 KB
/
exception handling.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# EXCEPTION HANDLIING
#Q1. Name and handle the exception occured in the following program:
'''
a=3
if a<4:
a=a/(a-3)
print(a)
'''
''' Ans. File "C:/Users/sony vaio/Desktop/exception handling.py", line 5, in <module>
a=a/(a-3)
ZeroDivisionError: division by zero '''
'''
a=3
try:
if a<4:
a=a/(a-3)
print(a)
except ZeroDivisionError as e:
print("Error occured: ",e)
'''
###############################
#Q2. Name and handle the exception occurred in the following program:
'''
l=[1,2,3]
print(l[3])
'''
#Ans. Error occured is IndexError
'''
try:
l=[1,2,3]
print(l[3])
except IndexError as e:
print("Error occured: ",e)
'''
##############################
#Q3. What will be the output of the following code:
'''
try:
raise NameError("Hi there") # Raise Error
except NameError:
print "An exception"
raise # To determine whether the exception was raised or n
'''
''''Output:-
An exception
Traceback (most recent call last):
File "hello.py", line 2, in <module>
raise NameError("Hi there") # Raise Error
NameError: Hi there'''
###################################
#Q4. What will be the output of the following code:
'''
def AbyB(a , b):
try:
c = ((a+b) / (a-b))
except ZeroDivisionError:
print "a/b result in 0"
else:
print c
'''
'''
# Driver program to test above function
AbyB(2.0, 3.0)
AbyB(3.0, 3.0)
'''
'''
Output:-
-5.0
a/b result in 0
'''
#####################################
#Q5. Write a program to show and handle following exceptions:
#1. Import Error
'''
try:
from threading import ABC
print(ABC)
except ImportError as e:
print("Error occured:",e)
'''
'''
#2. Value Error
try:
a=int(input("Enter number: "))
print(a)
except ValueError as e:
print("Error occured:",e)
'''
#3. Index Error
'''
l=[0,1,2]
try:
print(l[3])
except IndexError as e:
print("Error occured:",e)
'''
##########################
#Q6. Create a user-defined exception AgeTooSmallError() that warns the user when they have entered age less than 18.
#The code must keep taking input till the user enters the appropriate age number(less than 18).
'''
class Error(Exception):
def __init__(self):
super(Exception,self).__init__(self)
def ageTooSmallError(self, msg):
print(msg)
c=True
while c:
try:
age=int(input("Enter age"))
if age<18:
raise Error()
except Error as e:
e.ageTooSmallError("Warning: Age is less than 18")
else:
c=False
'''