OOP 2 Python Exception handling
What is Exception?
An exception is an event, which occurs during
the execution of a program that disrupts the
normal flow of the program's instructions.
In general, when a Python script encounters a
situation that it cannot cope with, it raises an
exception.
An exception is a Python object that represents
an error.
When a Python script raises an exception, it
must either handle the exception immediately
otherwise it terminates and quits.
Handling an Exception
If you have some suspicious code that may
raise an exception, you can defend your
program by placing the suspicious code in a
try: block.
After the try: block, include an except:
statement, followed by a block of code
which handles the problem.
Syntax;
try:
You do your operations here
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception, then execute this block.
e.g.
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print("Error: can\'t find file or read data")
else:
print("Written content in the file successfully")
fh.close()
Output
Written content in the file successfully
try:
fh = open("testfile", "r")
fh.write("This is my test file for exception handling!!")
except IOError:
print("Error: file not written, check permissions")
else:
print("Written content in the file successfully")
fh.close()
Output
Error: file not written, check permissions