5
5
6
6
This program demonstrates the exception handling in python code.
7
7
'''
8
+ def read_file_n_display ():
9
+ print ('Working code to read and display the file.' )
10
+ fh = open ('sample.txt' )
11
+ for line in fh :print (line .strip ())
8
12
9
- def main ():pass
13
+ def simple_exception_demo ():
14
+ try :
15
+ fh = open ('xsample.txt' )# file handle
16
+ except :
17
+ print ('Cannot open the file.' )
18
+ else :
19
+ for line in fh :
20
+ print (line .strip ())
10
21
22
+ def exception_demo ():
23
+ print ('Notice:\n In try block, the code execution stops at the line where exception occurs.\
24
+ The further code is not executed.' )
25
+
26
+ try :
27
+ fh = open ('xsample.txt' )
28
+ for line in fh :print (line .strip ())
29
+ except Exception as e :
30
+ print ('Something happened.' )
31
+ print (e )
32
+
33
+ def exception_demo_specific_exception ():
34
+ print ('Demo for exception handling with specific exception.' )
35
+ try :
36
+ fh = open ('xsample.txt' )# file handle
37
+ except IOError as e :
38
+ print ('Cannot open the file.' ,e )
39
+ else :
40
+ for line in fh :
41
+ print (line .strip ())
42
+
43
+ def main ():
44
+ simple_exception_demo ()
45
+ print ()
46
+ exception_demo ()
47
+ print ()
48
+ exception_demo_specific_exception ()
49
+ print ()
50
+ read_file_n_display ()
51
+
11
52
if __name__ == '__main__' :main ()