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 9a77d60

Browse files
Add functions for exception handling demonstration.
1 parent 11da25c commit 9a77d60

File tree

1 file changed

+42
-1
lines changed

1 file changed

+42
-1
lines changed

‎ExceptionIntro/src/exceptionintro.py‎

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,48 @@
55
66
This program demonstrates the exception handling in python code.
77
'''
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())
812

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())
1021

22+
def exception_demo():
23+
print('Notice:\nIn 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+
1152
if __name__ == '__main__':main()

0 commit comments

Comments
(0)

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