-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathException Handling.py
564 lines (460 loc) · 15.7 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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
'''
EXCEPTION HANDLING:
--------------------
* In any programming language there are 2-types of error are possible.
1.Syntax Errors
2.Runtime Errors
1. Syntax Error:
-----------------
* The errors which occurs because of invalid syntax are called syntax errors or parsing errors.
EX:
x = 10
if x == 10
print("Hello") # SyntaxError: expected ':'
Ex:
print 'Hi'
SyntaxError: Missing parentheses in call to 'print'.
Note:
* Programmer is responsible to correct these errors. Once all syntax errors are corrected then only program execution will be started.
2. Runtime Errors:
-------------------
* It is also called as exceptions.
* While executing the program if something goes wrong because of end user input or programming logic or memory problems etc then we will get runtime errors.
Ex:
print(10/0)==>ZeroDivisionError
print(10/'ten')==>TypeError
int('ten')==>ValueError
Note:
* Exception handling concept is applicable for runtime errors not for syntax errors.
What is an Exception?
---------------------------------
An unwanted and unexpected event that distrubs normal flow of the program is called as an exception.
Ex:
ZeroDivisionError
ValueError
TyrePuncheredError
SleepingError
* It is highly recommended to handle exceptions.
The main objective of exception handling is Graceful Termination of the program(i.e we should not block our resources and we should not miss anything).
* Exception handling does not mean repairing exception.
We have to define alternative way to continue rest of the program normally.
Q.What is an Exception?
Q.What is the purpose of Exception Handling?
Q.What is the meaning of Exception Handling?
Default exception handling in python
--------------------------------------------------------
* Every exception in python is an object. For every exception type the corresponding classes are available.
* Whenever an exception occurs PVM will create the corresponding exception object and will check for handling code.
If the handling code is not available then python interprter terminates the program abnormally and prints corresponding ex ception information to the console.
* The rest of the program wont be executed.
Ex:
print('Hello')
print(10/0)
print('Hi')
Customized exception handling by using try-except:
------------------------------------------------------------------------------
* The code which may raise exception is called as risky code and we have to take risky code inside try block.
The corresponding handling code we have to take inside except block.
* Syn:
try:
Risky code
except XXX:
Handling code/Alternative code
Ex:
print('stmt-1')
try:
print(10/0)
except ZeroDivisionError:
print(10/2)
print('stmt-3')
Control flow in try-except block:
-------------------------------------------------
Ex:
try:
stmt-1
stmt-2
stmt-3
except XXX:
stmt-4
stmt-5
Case-1:If there is no exception.
1,2,3,5 Normal Termination.
Case-2:If an exception raised at stmt-2 and corresponding except block is matched.
1,4,5 Graceful Termination.
Case-3:If an exception raised at stmt-2 and corresponding except block is not matched.
1 Abnormal Termination.
Case-4:If an exception raised at stmt-4 or stmt-5 then it always abnormal termination.
Conclusions:
-------------------
1).Within the try block if anywhere exception raised then rest of the try block wont be executed eventhough we handled that exception. Hence we have to take only risky code inside the try block and length of the try block should be as less as possible.
2).In addition to try block, there may be chance of raising exception inside except block also.
3).If any statement which is not part of try block raises an exception then it is always abnormal termination.
How to print exception information?
------------------------------------------------------
try:
print(10/0)
except ZeroDivisionError as msg:
print("Exception raised and it's description is:",msg)
try with multiple except blocks:
---------------------------------
--> The way of handling exception is varied exception to exception. Hence for every exception type a separate except block we have to provide. i.e
try with multiple except block is possible and recommended.
--> If try with multiple except blocks are available then based on raised exception the corresponding except block will be executed.
try:
x = int(input('Enter first number:'))
y = int(input('Enter second number:'))
print(x/y)
except ZeroDivisionError:
print("Can't devide with zero")
except ValueError:
print('Pls provide int values')
-->If try with multiple except blocks available then the order of these except blocks is important. Python interpreter will always consider top to bottom until matched except block identified.
try:
x = int(input('Enter first number:'))
y = int(input('Enter second number:'))
print(x/y)
except ArithmeticError:
print('ArithmeticError')
except ZeroDivisionError:
print("ZeroDivisionError")
Single except block that can handle multiple exceptions:
----------------------------------------------------------
try:
x = int(input('Enter first number:'))
y = int(input('Enter second number:'))
print(x/y)
except (ZeroDivisionError,ValueError) as msg:
print("Pls provide valid numbers only problem is:",msg)
-->We can use default except block to handle any type of exception.
-->In default except block generally we can print normal error messages.
Syn:
except:
statements
try:
x = int(input('Enter first number:'))
y = int(input('Enter second number:'))
print(x/y)
except ZeroDivisionError:
print("ZeroDivisionError:Can't devide with zero")
except :
print('DefaultExcept:Pls provide valid input')
Note:
If try with multiple except blocks available then the default except block should be last, otherwise we will get SyntaxError.
SyntaxError: default 'except:' must be last
Various combinations of except block
--------------------------------------------------------
1.except ZeroDivisionError:
2.except ZeroDivisionError as msg:
3.except (ZeroDivisionError,ValueError):
4.except (ZeroDivisionError,ValueError) as msg:
5.except:
finally block:
----------------
--> It is not recommend to maintain clean up code(Resource deallocation core or resource releasing code) inside try block because there is no guarantee for the execution of every statement inside try block always.
--> It is not recommend to maintain clean up code inside except block, because if there is no exception then except block wont be executed.
--> Hence we required some place to maintain clean up code which should be executed always irrespective of whether exception raised or not raised and whether exception handled or not handled.
such type of best place is nothing but finally block.
--> Hence the main purpose of finally block is to maintain clean up code.
Syn:
try:
Rsiky code
except :
Handling code
finally:
Clean up code
Note:
There is only one situation where finally block wont be executed i.e whenever we are using os._exit(0) function.
Whenever we are using os._exit(0) function then PVM itself will be shutdown. In this particular case finally block won't be executed.
import os
try:
print('try')
os._exit(0)
except NameError:
print('except')
finally:
print('finally')
os._exit(0):0 represents status code and it indicates normal termination.
* Control floe of try-except -finally
-------------------------------------------------
try:
stmt-1
stmt-2
stmt-3
except:
stmt-4
finally:
stmt-5
stmt-6
Case-1:If there is no exception
1,2,3,5,6 Normal Termination
Case-2:If an exception raised in stmt-2 and the corresponding except block matched.
1,4,5,6 Graceful termination
Case-3:If an exception raised in stmt-2 and the corresponding except block not matched.
1,5 Abnormal termination
Case-4:An exception raised at stmt-5 or stmt-6 then it is always abnormal termination.
Case-5:An exception raised at stmt-4 then it always abnormal termination but before that finally block will be executed.
Nested try-except-finally block:
----------------------------------------------
* Generally risky code we have to take inside outer try block and too much risky code we have to take inner try block.
* Inside inner try block if any exception raised then inner except block is responsible to handle.
* If unable to handle then outer except block is responsible to handle.
try:
print('Outer try block')
try:
print('Inner try block')
print(10/0)
except NameError:
print('Inner except block')
finally:
print('Inner finally block')
except:
print('Outer except block')
finally:
print('Outer finally block')
else block with try-except-finally:
-------------------------------------------------
-->We can use else block with try-except-finally block
-->else block will be executed if and only if there are no exceptions inside try block.
Syn:
-------
try:
Risky code
except:
will be executed if exception inside try
else:
will be executed if there is no exception inside try
finally:
will be executed whether exception raised or notraised handled or not handled.
Ex:
-----
try:
print('try')
print(10/0)===>Line-1
except:
print('except')
else:
print('else')
finally:
print('finally')
-->If we comment Line-1 then else block will be executed bcoz there is no exception inside try. In this case the output is:try else finally
-->If we are not commenting Line-1 then else block wont be executed bcoz there is an exception inside try block. In this case output is:try except finally
'''
# x = 10
# if x == 10
# print("Hi")
# print 'Hi'
print(10/0) #==>ZeroDivisionError
print(10/'ten') #==>TypeError
int('ten') #==>ValueError
print('statement-1')
try:
print(10/0)
except ZeroDivisionError:
print(10/2)
print('statement-3')
try:
print(10/0)
except ZeroDivisionError as msg:
print("Exception raised and it's description is:", msg)
# Ex:
try:
x = int(input('Enter first number:'))
y = int(input('Enter second number:'))
print(x/y)
except ZeroDivisionError:
print("Can't devide with zero")
except ValueError:
print('Pls provide int values')
try:
x = int(input('Enter first number:'))
y = int(input('Enter second number:'))
print(x/y)
except ArithmeticError:
print("Can't devide with zero")
except ZeroDivisionError:
print('Pls provide int values')
# Single except block that can handle multiple exceptions
try:
x = int(input('Enter first number:'))
y = int(input('Enter second number:'))
print(x/y)
except (ZeroDivisionError,ValueError) as msg:
print("Pls provide valid numbers only problem is:",msg)
# Default except block:
# ----------------------
try:
x = int(input('Enter first number:'))
y = int(input('Enter second number:'))
print(x/y)
except ZeroDivisionError:
print("ZeroDivisionError:Can't devide with zero")
except :
print('DefaultExcept:Pls provide valid input')
# finally block
# ---------------
# Case-1:If there is no exception
# ----------------------------------------------
try:
print('try')
except:
print('except')
finally:
print('finally')
# o/p:try finally
# Case-2:If there is an exception raised but handled
# ---------------------------------------------------------------------------
try:
print('try')
print(10/0)
except ZeroDivisionError:
print('except')
finally:
print('finally')
# o/p:try except finally
# Case-3:If there is an exception raised but not handled
# ---------------------------------------------------------------------------------
try:
print('try')
print(10/0)
except NameError:
print('except')
finally:
print('finally')
# o/p:try finally Abnormal termination.
# Nested try-except-finally block
# ----------------------------------------------
try:
print('Outer try block')
try:
print('Inner try block')
print(10/0)
except NameError:
print('Inner except block')
finally:
print('Inner finally block')
except:
print('Outer except block')
finally:
print('Outer finally block')
# else block with try-except-finally:
# ----------------------------------------------
try:
print('try')
print(10/0)
# print(10/0)===>Line-1
except:
print('except')
else:
print('else')
finally:
print('finally')
'''
Types of Exceptions:
----------------------
1. Predefined Exceptions
2. User Defined Exceptions
1. Predefined Exceptions:
---------------------------
* Also know as inbuilt exceptions.
* The exceptions which are raised automatically by python virtual machine whenever a particular event occurs, are called as pre-defined exceptions.
* Ex:
ZeroDivisionError
ValueError
TypeError
2. User defined exceptions:
-----------------------------
* Also known as customized exceptions or programatic exceptions.
* some times we have to define and raise exceptions explicitly to indicate that something goes wrong, such type of exceptions
are called as user defined exceptions. or customized exceptions.
* programmer is responsible to define these exceptions and python not having any idea about these. Hence we have to raise explicitly based on out requirement by using raise keyword.
* Ex:
InsufficientFundsException
InvalidAgeException
InvalidChoiceException
InvalidInputException
InvalidInputException
InvalidInputException
InvalidInput
'''
# How to define and raised customized exceptions?
# --------------------------------------------------
# syn :
# class ClassName(Exception):
# def __init__(self,args):
# self.msg = arg
# Ex:
class TooYoungException(Exception):
def __init__(self,args):
self.msg = args
class TooOldException(Exception):
def __init__(self,args):
self.msg = args
age = eval(input("Enter Age: "))
if age > 18:
raise TooYoungException('Plz wait some more time you will get best match soon!!!!!')
elif age < 18:
raise TooOldException('Your age already crossed marriage age...no chance of getting marriage')
else:
print('You will get match details soon by email..........')
# Pickling and Unpickling of objects:
# ==============================
# -->Sometimes we have to write total state of object to the file and we have to read total object from the file.
# -->The process of writing state of object to the file is called as pickling and the process of reading state of an object from the file is called as unpickling.
# -->We can implement pickling and unpickling by using pickle module.
# -->pickle module contains dump() function to perform pickling.
# pickle.dump(object,f)
# -->pickle module contains load() function to perform unpickling.
# pickle.load(f)
# Q.writting and reading state of object by using pickle module
# -------------------------------------------------------------------------------------------
import pickle
class Employee:
def __init__(self,eno,ename,eaddr):
self.eno = eno
self.ename = ename
self.eaddr = eaddr
def display(self):
print(self.eno,'\t',self.ename,'\t',self.eaddr)
with open('emp.dat','wb')as f:
e = Employee(101,'Radhika','Hyd')
pickle.dump(e,f)
print('Pickling of Employee object completed.....')
with open('emp.dat','rb') as f:
obj = pickle.load(f)
print('Printing employee information after unpickling....')
obj.display()
# Q : Writing multiple employee objects to the file.
# emp.py
# ---------
class Employee:
def __init__(self,eno,ename,eaddr):
self.eno = eno
self.ename = ename
self.eaddr = eaddr
def display(self):
print(self.eno,'\t',self.ename,'\t',self.eaddr)
# pick.py
# ---------
import pickle,emp
f = open('emp.dat','wb')
n = int(input('Enter number of employees:'))
for i in range(n):
eno = int(input('Enter employee number: '))
ename = input('Enter employee name: ')
eaddr = input('Enter employee address: ')
e = emp.Employee(eno,ename,eaddr)
pickle.dump(e,f)
print('Employee objects pickled successfully....')
# unpick.py
# --------------
import pickle,emp
f = open('emp.dat','rb')
print('Employee Details:')
while True:
try:
obj = pickle.load(f)
obj.display()
except EOFError:
print('All employees completed')
break
f.close()