@@ -18,7 +18,7 @@ def simple_exception_demo():
18
18
else :
19
19
for line in fh :
20
20
print (line .strip ())
21
-
21
+
22
22
def exception_demo ():
23
23
print ('Notice:\n In try block, the code execution stops at the line where exception occurs.\
24
24
The further code is not executed.' )
@@ -40,6 +40,23 @@ def exception_demo_specific_exception():
40
40
for line in fh :
41
41
print (line .strip ())
42
42
43
+ def raise_exception_demo ():
44
+ print ('Demonstration of raising an exception in python.' )
45
+
46
+ try :
47
+ for line in readfile ('sample.doc' ):print (line .strip ())
48
+ except IOError as e :
49
+ print ('File cannot be found,' ,e )
50
+ except ValueError as e :
51
+ print ('Bad filename.' ,e )
52
+
53
+ def readfile (filename ):
54
+ if filename .endswith ('.txt' ):
55
+ fh = open (filename )
56
+ return fh .readlines ()# This function returns an iterator
57
+ else :
58
+ raise ValueError ('Filename must end with\' .txt\' . Please check the file format.' )
59
+
43
60
def main ():
44
61
simple_exception_demo ()
45
62
print ()
@@ -48,5 +65,7 @@ def main():
48
65
exception_demo_specific_exception ()
49
66
print ()
50
67
read_file_n_display ()
68
+ print ()
69
+ raise_exception_demo ()
51
70
52
71
if __name__ == '__main__' :main ()