1
+ #What is exception handling
2
+ '''
3
+ Exception handling is the process of responding to unwanted
4
+ or unexpected events when a computer program runs. Exception
5
+ handling deals with these events to avoid the program or
6
+ system crashing, and without this process,
7
+ exceptions would disrupt the normal operation of a program.
8
+
9
+ a=1
10
+ while a:
11
+ a=a+1
12
+ print(a)
13
+
14
+ '''
15
+ #Python Exceptions
16
+ '''
17
+ A Python program terminates as soon as it encounters an error.
18
+ In Python, an error can be a "syntax error" or an "exception".
19
+ '''
20
+ '''
21
+ Syntax errors: Also known as parsing errors, are perhaps the
22
+ most common kind of complaint you get while you are still
23
+ learning Python.
24
+
25
+ Exceptions: This type of error occurs whenever syntactically
26
+ correct Python code results in an error. The last line of
27
+ the message indicated what type of exception error you ran into.
28
+
29
+ Here are all of Pythons built-in exception
30
+ 1.ArithmeticError Raised when an error occurs in numeric calculations
31
+ 2.AssertionError Raised when an assert statement fails
32
+ 3.AttributeError Raised when attribute reference or assignment fails
33
+ 4.Exception Base class for all exceptions
34
+ 5.EOFError Raised when the input() method hits an "end of file"
35
+ condition (EOF)
36
+ 6.FloatingPointError Raised when a floating point calculation fails
37
+ 7.GeneratorExit Raised when a generator is closed (with the close()
38
+ method)
39
+ 8.ImportError Raised when an imported module does not exist
40
+ 9.IndentationError Raised when indentation is not correct
41
+ 10.IndexError Raised when an index of a sequence does not exist
42
+ 11.KeyError Raised when a key does not exist in a dictionary
43
+ 12.KeyboardInterrupt Raised when the user presses Ctrl+c, Ctrl+z or
44
+ Delete
45
+ 13.LookupError Raised when errors raised cant be found
46
+ 14.MemoryError Raised when a program runs out of memory
47
+ 15.NameError Raised when a variable does not exist
48
+ 16.NotImplementedError Raised when an abstract method requires
49
+ an inherited class to override the method
50
+ 17.OSError Raised when a system related operation causes an error
51
+ 18.OverflowError Raised when the result of a numeric calculation is
52
+ too large
53
+ 19.ReferenceError Raised when a weak reference object does
54
+ not exist
55
+ 20.RuntimeError Raised when an error occurs that do not belong
56
+ to any specific expections
57
+ 21.StopIteration Raised when the next() method of an iterator
58
+ has no further values
59
+ 22.SyntaxError Raised when a syntax error occurs
60
+ 23.TabError Raised when indentation consists of tabs or spaces
61
+ 24.SystemError Raised when a system error occurs
62
+ 25.SystemExit Raised when the sys.exit() function is called
63
+ 26.TypeError Raised when two different types are combined
64
+ 27.UnboundLocalError Raised when a local variable is referenced
65
+ before assignment
66
+ 28.UnicodeError Raised when a unicode problem occurs
67
+ 29.UnicodeEncodeError Raised when a unicode encoding problem occurs
68
+ 30.UnicodeDecodeError Raised when a unicode decoding problem occurs
69
+ 31.UnicodeTranslateError Raised when a unicode translation problem
70
+ occurs
71
+ 32.ValueError Raised when there is a wrong value in a specified
72
+ data type
73
+ 33.ZeroDivisionError Raised when the second operator in a
74
+ division is zero
75
+ '''
76
+
77
+ #Syntax error
78
+ '''
79
+ a=2
80
+ a++ #Error
81
+ a=a+1
82
+ a
83
+ '''
84
+ #ZeroDivisionError
85
+ a = 2
86
+ c = 0
87
+ d = a / c
88
+ '''
89
+ Traceback (most recent call last):
90
+ File "<stdin>", line 1, in <module>
91
+ "ZeroDivisionError: division by zero"
92
+ '''
93
+ #The Raising an Exception
94
+ '''
95
+ We can use raise to throw an exception if a condition occurs.
96
+ The statement can be complemented with a custom exception.
97
+
98
+ If a condition does not meet our criteria but is correct according to
99
+ the Python interpreter, we can intentionally raise an exception using
100
+ the raise keyword
101
+
102
+ If you want to throw an error when a certain condition occurs
103
+ using raise, you could go about it like this:
104
+ '''
105
+ #Example1
106
+ x = 10
107
+ if x > 5 :
108
+ raise Exception ('x should not exceed 5. The value of x was: {}' .format (x ))
109
+
110
+ '''
111
+ Traceback (most recent call last):
112
+ File "<input>", line 4, in <module>
113
+ Exception: x should not exceed 5. The value of x was: 10
114
+ '''
115
+
116
+ #Example2
117
+ num = [3 , 4 , 5 , 7 ]
118
+ if len (num ) > 3 :
119
+ raise Exception ( f"Length of the given list must be less than or equal to 3 but is { len (num )} " )
120
+ '''
121
+ Traceback (most recent call last):
122
+ File "<stdin>", line 2, in <module>
123
+ Exception: Length of the given list must be less than or equal to 3 but is 4
124
+ '''
125
+
126
+ #The AssertionError Exception
127
+ '''
128
+ The simplest way to understand an assertion to check the condition.
129
+ If it finds that the condition is true, it moves to the next line of
130
+ code, and If not, then stops all its operations and throws an error.
131
+ It points out the error in the code.
132
+ assert Expressions[, Argument]
133
+
134
+ If this condition turns out to be True, then that is excellent!
135
+ The program can continue. If the condition turns out to be False,
136
+ you can have the program throw an AssertionError exception.
137
+ '''
138
+ #Example1
139
+ def square_root ( Number ):
140
+ assert ( Number < 0 ), "Give a positive integer"
141
+ return Number ** (1 / 2 )
142
+
143
+ #Calling function and passing the values
144
+ print ( square_root (- 36 ))
145
+ print ( square_root (36 ))
146
+
147
+ '''
148
+ Output
149
+ (3.6739403974420594e-16+6j)
150
+
151
+ Traceback (most recent call last):
152
+ File "<stdin>", line 1, in <module>
153
+ File "<stdin>", line 2, in square_root
154
+ AssertionError: Give a positive integer)
155
+ '''
156
+ #Example2
157
+ def avg (scores ):
158
+ assert len (scores ) != 0 ,"The List is empty."
159
+ return sum (scores )/ len (scores )
160
+ scores2 = [67 ,59 ,86 ,75 ,92 ]
161
+ print ("The Average of scores2:" ,avg (scores2 ))
162
+ scores1 = []
163
+ print ("The Average of scores1:" ,avg (scores1 ))
164
+
165
+ '''
166
+ The Average of scores2: 75.8
167
+
168
+ Traceback (most recent call last):
169
+ File "<stdin>", line 1, in <module>
170
+ File "<stdin>", line 2, in avg
171
+ AssertionError: The List is empty.
172
+ '''
173
+
174
+ #The try and except Block
175
+ '''
176
+ In Python, we catch exceptions and handle them using try and except
177
+ code blocks. The try clause contains the code that can raise an
178
+ exception, while the except clause contains the code lines that handle
179
+ the exception. Let's see if we can access the index from the array,
180
+ which is more than the array's length, and handle the resulting
181
+ exception.
182
+ '''
183
+ #Example
184
+ a = ["Python" , "Exceptions" , "try and except" ]
185
+ try :
186
+ #looping through the elements of the array a, choosing a range that goes beyond the length of the array
187
+ for i in range ( 4 ):
188
+ print ( "The index and element from the array is" , i , a [i ] )
189
+ #if an error occurs in the try block, then except block will be executed by the Python interpreter
190
+ except :
191
+ print ("Index out of range" )
192
+ '''
193
+
194
+ Output
195
+ The index and element from the array is 0 Python
196
+ The index and element from the array is 1 Exceptions
197
+ The index and element from the array is 2 try and except
198
+ Index out of range
199
+
200
+ '''
201
+ #Try with Else Clause
202
+ '''
203
+ If there is no exception, this code block will be executed by
204
+ the Python interpreter
205
+ '''
206
+ def reciprocal ( num1 ):
207
+ try :
208
+ reci = 1 / num1
209
+ except ZeroDivisionError :
210
+ print ( "We cannot divide by zero" )
211
+ else :
212
+ print ( reci )
213
+ # Calling the function and passing values
214
+ reciprocal ( 4 )
215
+ reciprocal ( 0 )
216
+
217
+ '''
218
+ 0.25
219
+ "We cannot divide by zero"
220
+ '''
221
+
222
+ #Finally Keyword in Python
223
+ '''
224
+ The finally keyword is available in Python, and it is always used
225
+ after the try-except block. The finally code block is always executed
226
+ after the try block has terminated normally or after the try block
227
+ has terminated for some other reason.
228
+ '''
229
+ # Python code to show the use of finally clause
230
+
231
+ try :
232
+ div = 4 / 0
233
+ print ( div )
234
+ # this block will handle the exception raised
235
+ except ZeroDivisionError :
236
+ print ( "Attepting to divide by zero" )
237
+ # this will always be executed no matter exception is raised or not
238
+ finally :
239
+ print ( 'This is code of finally clause' )
240
+
241
+ '''
242
+ Output
243
+ Atepting to divide by zero
244
+ This is code of finally clause
245
+ '''
0 commit comments