Today, we discuss about the following :
1) Try block in Python
2) finally block
3) Exceptions
-> In the following example, we can catch exceptions occurred in the code.
-> Keep the code in try block, when an exception is there, it is being caught by except
-> Finally block will be called at the last after the end of execution of the block.
-> In this example, there are few well know exceptions like FileNotFoundError, IOError, EOFError, ValueError
read.txt (Input File)
exceptions_test.py
You may also wish to read Object Oriented Concepts in Python as mentioned :
Python Class and Object Example
Inheritance in Python
Packages in Python
1) Try block in Python
2) finally block
3) Exceptions
-> In the following example, we can catch exceptions occurred in the code.
-> Keep the code in try block, when an exception is there, it is being caught by except
-> Finally block will be called at the last after the end of execution of the block.
-> In this example, there are few well know exceptions like FileNotFoundError, IOError, EOFError, ValueError
read.txt (Input File)
Abraham Lincoln Mother Teresa Paul Coelho
exceptions_test.py
import time
import sys
try:
f = open('read.txt', 'r')
while True: # our usual file-reading idiom
line = f.readline()
if len(line) == 0:
break
time.sleep(0.5) #1/2 sec
print(line)
except FileNotFoundError:
print('\n File NOT Found Error')
sys.exit
except IOError:
print('\n IO Error')
sys.exit
except EOFError:
print('\nWhy did you do an EOF on me?')
sys.exit
except ValueError:
print("\nValue Error.")
sys.exit
finally:
f.close()
print('Cleaning up...closed the file')
You may also wish to read Object Oriented Concepts in Python as mentioned :
Python Class and Object Example
Inheritance in Python
Packages in Python
No comments:
Post a Comment