-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtry-except.py
More file actions
119 lines (93 loc) · 2.2 KB
/
try-except.py
File metadata and controls
119 lines (93 loc) · 2.2 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
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
#########################################
# #
# #
# TRY BLOCK #
# #
#########################################
# compiled time error : means we missing colon or comma like that
# run time error : means it will occur error when we running
# for e.g.,
a = 10 / 0
print(a) # it will give runtime error : zero division error
############################
try:
a = 10/0
except Exception as e :
print(e)
# it will give program o/p as division by zero
##############################
# try except else
try :
n = int(input('')
a = 10 / n
except Exception as e
print(e)
else :
print(a)
##################################
# try except finally
# finally if we have except or we don't have except it will print finally
try :
n = int(input('')
a = 10 / n
except Exception as e
print(e)
else :
print(a)
finally :
print('Tq u')
######################################
# type of exception
print(dir(locals()['__builtins__']))
# it will print all bultin exception'
print(len(dir(locals()['__builtins__'])))
#######################################
# name error exception
# if the definition or variable anything is not there it will exception
# if we want to print a there is no a defined value so it will take exception
try :
print(a)
except Exception as e
print(e)
# or we can print customized message
print('a is not defined')
#################################
try :
print(10/0)
except ZeroDivisionError as e:
print(" denominator can't be zero ")
###############
try :
print('rock')
except ValueError as e :
print(e)
print(' enter values only [numbers]')
################
try :
a = [ 10 , 20 , 30 , 40 ]
print(a[0])
print(a[100])
# there is no index 100
except IndexError :
print('invalid index')
###################
try :
f = open('sample.txt')
except FileNotFoundError :
print('file not found')
else :
print(f.read())
#####################
# handling multiple exception
try :
a = 10/20
print(a)
b = [ 10 , 20 , 30 ]
print(b[10])
# index 10 is not there
except ZeroDivisionError :
print('denominator can"t be zero')
except IndexError :
print('Invalid Index')
# we can print multiple exception
################################################################