Exception Handling
Exception Handling
This kind of a try-except statement catches all the exceptions that occur.
Using this kind of try-except statement is not considered a good
programming practice, though, because it catches all exceptions but does
not make the programmer identify the root cause of the problem that may
occur.
The except clause with multiple exceptions:
You can also use the same except statement to handle multiple
exceptions as follows:
try:
You do your operations here;
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception list, then
execute this block
.......................
else:
If there is no exception then execute this block.
Standard Exceptions:
Here is a list standard Exceptions available in Python: Standard
Exceptions
The try-finally clause:
You can use a finally: block along with a try: block. The finally block is a
place to put any code that must execute, whether the try-block raised an
exception or not. The syntax of the try-finally statement is this:
try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................
Note that you can provide except clause(s), or a finally clause, but not
both. You can not use else clause as well along with a finally clause.
Example:
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
finally:
print "Error: can\'t find file or read data"