8 Exception Handling
8 Exception Handling
EXCEPTIONAL HANDLING
Python Exceptions Handling
Python provides two very important features to handle any unexpected
error in your Python programs and to add debugging capabilities in
them:
– Exception Handling: This would be covered in this tutorial.
– Assertions: This would be covered in Assertions in Python
tutorial.
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 can't
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 would terminate and come out.
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 as elegantly as possible.
Syntax:
try:
You do your operations here;
......................
except Exception I:
If there is ExceptionI, then execute this block.
except Exception II:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
Here are few important points above the above mentioned syntax:
• A single try statement can have multiple except statements. This is
useful when the try block contains statements that may throw
different types of exceptions.
• You can also provide a generic except clause, which handles any
exception.
• After the except clause(s), you can include an else-clause. The code
in the else-block executes if the code in the try: block does not
raise an exception.
• The else-block is a good place for code that does not need the try:
block's protection.
Example:
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()
• This will produce following result:
Written content in the file successfully
The except clause with no exceptions:
You can also use the except statement with no exceptions
defined as follows:
try:
You do your operations here;
......................
except:
If there is any exception, then execute this
block. ......................
else:
If there is no exception then execute this block.
1. Syntax Errors
2. Semantic Errors
3. Run Time Errors.
4. Logical Errors.
1. Syntax Errors
) Missing
2. Semantic Errors
What is an exception?
For Example
Handling Exceptions
Handling Exceptions
For Example
Handling Exceptions