Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit cf92f17

Browse files
Add function for Raising exception.
1 parent 9a77d60 commit cf92f17

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed

‎ExceptionIntro/src/exceptionintro.py

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ def simple_exception_demo():
1818
else:
1919
for line in fh:
2020
print(line.strip())
21-
21+
2222
def exception_demo():
2323
print('Notice:\nIn try block, the code execution stops at the line where exception occurs. \
2424
The further code is not executed.')
@@ -40,6 +40,23 @@ def exception_demo_specific_exception():
4040
for line in fh:
4141
print(line.strip())
4242

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+
4360
def main():
4461
simple_exception_demo()
4562
print()
@@ -48,5 +65,7 @@ def main():
4865
exception_demo_specific_exception()
4966
print()
5067
read_file_n_display()
68+
print()
69+
raise_exception_demo()
5170

5271
if __name__ == '__main__':main()

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /