-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path14.python_exception_handling.py
More file actions
67 lines (47 loc) · 1.41 KB
/
14.python_exception_handling.py
File metadata and controls
67 lines (47 loc) · 1.41 KB
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
# Example : Catching Exceptions in Python
print('>>>> Example - 1 >>>>')
randomList = ['a', 0, 2]
for entry in randomList:
try:
print("The entry is", entry)
r = 1 / int(entry)
except Exception as error:
print("Oops! error occurred - {}".format(error))
# Example : Python try... except... finally
print('\n')
print('>>>> Example - 2 >>>>')
randomList = ['a', 0, 2]
for entry in randomList:
try:
print("The entry is", entry)
r = 1 / int(entry)
except Exception as error:
print("Oops! error occurred - {}".format(error))
finally:
print('It will always execute')
# Example : User-Defined Exception in Python
print('\n')
print('>>>> Example - 3 >>>>')
class Error(Exception):
"""Base class for other exceptions"""
pass
class ValueTooSmallError(Error):
"""Raised when the input value is too small"""
pass
class ValueTooLargeError(Error):
"""Raised when the input value is too large"""
pass
number = 10
while True:
try:
i_num = int(input("Enter a number: "))
if i_num < number:
raise ValueTooSmallError
elif i_num > number:
raise ValueTooLargeError
break
except ValueTooSmallError:
print("This value is too small, try again!")
except ValueTooLargeError:
print("This value is too large, try again!")
print("Congratulations! You guessed it correctly.")