-
Notifications
You must be signed in to change notification settings - Fork 0
/
ExceptionHandling(Try).py
102 lines (88 loc) · 2.25 KB
/
ExceptionHandling(Try).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
# try:
# # code that may cause exception
# except:
# # code to run when exception occurs
# try:
# numerator = 10
# denominator = 0
#
# result = numerator / denominator
#
# print(result)
#
# except ZeroDivisionError:
# print("Error: Denominator cannot be 0.")
# Output: Error: Denominator cannot be 0.
# try:
#
# even_numbers = [2, 4, 6, 8]
# print(even_numbers[5])
#
# except IndexError:
# print("Index Out of Bound.")
# Python try...finally
# In Python, the final block is always executed no matter whether there is an exception or not.
# The final block is optional. And, for each try block, there can be only one finally block.
# try:
# numerator = 10
# denominator = 0
#
# result = numerator / denominator
#
# print(result)
#
# except ZeroDivisionError:
# print("Error: Denominator cannot be 0.")
#
# finally:
# print("This is finally block.")
# Example for Exceptional Handling
a = 3
b = 6
try:
print("resource Open")
print(a / b)
k = int(input("Enter a number"))
print(k)
except ZeroDivisionError as e:
print("Hey, You cannot divide a Number by Zero", e)
except ValueError as e:
print("Invalid Input")
except Exception as e:
print("Something went Wrong...")
finally:
print("resource Closed")
# Example
# try:
# print('try block')
# x = int(input('Enter a number: '))
# y = int(input('Enter another number: '))
# z = x / y
# except ZeroDivisionError:
# print("except ZeroDivisionError block")
# print("Division by 0 not accepted")
# else:
# print("else block")
# print("Division = ", z)
# finally:
# print("finally block")
# x = 0
# y = 0
# print("Out of try, except, else and finally blocks.")
# Example with function
# def simple_interest(amount, year, rate):
# try:
# if rate > 100:
# raise ValueError(rate)
# interest = (amount * year * rate) / 100
# print('The Simple Interest is', interest)
# return interest
# except ValueError:
# print('interest rate is out of range', rate)
#
#
# print('Case 1')
# simple_interest(800, 6, 8)
#
# print('Case 2')
# simple_interest(800, 6, 800)