Exception Handling in Python

Exception Handling in Python

Errors in any programming language are of three types
1.    Syntax errorsalso known as parsing errors – errors in the structure and rules of the program
2.    Semantic errors – also known as logical errors – when is program is syntactically correct but does not provide expected output due to errors in the programming logic
3.    Runtime errors – also known as EXCEPTIONS. These are errors that occur during the execution of a program that disrupts the normal flow of the program's instructions. If the exception is not handled the program terminates abruptly.


Standard Exceptions in Python:
Exception
Description
Exception
Base class for all exceptions
ArithmeticError
errors that occur for numeric calculation
ZeroDivisionError
division or modulo by zero takes place for all numeric types
AttributeError
failure of attribute reference or assignment
ImportError
import statement fails
IndexError
index is not found in a sequence
KeyError
specified key is not found in the dictionary
NameError
identifier is not found in the local or global namespace
IOError
input/ output operation fails
IndentationError
indentation is not specified properly
TypeError
operation or function is attempted that is invalid for the specified data type.
ValueError
built-in function for a data type has the valid type of arguments


Exception Handling in Python:
Exception in Python is handled using keywords: try – except – else – finally keywords. Statements that may cause run time errors are placed in try block. Try blocks are followed by except block which contain the code to handle the error as elegantly as possible. If the try block contains statements that may throw different types of exceptions multiple except statements can be used. Generic except clause can handle any exception type. After except block, an else block can be used. The code in the else block executes if the code in the try block does not raise an exception. Generally code in the program which will not cause errors are placed in else block.
General form of try-except-else-finally
try:
          // statement block which may cause errors
except (<exception type>):
          // statement block to handle specific error
except:
          // statement block to handle generic errors
else:
          // statement block which do not cause errors
finally:
          // statements which are executed whether an exception occurs or not

The try statement works as follows.
  • First, the statements in the try block are executed.
  • If no exception occurs, the try block is fully executed and except block is skipped. The else and finally blocks are fully executed.
  • If an exception occurs during execution of a statement in the try block, the rest of the statements in the try block is skipped. Control passes to except block whose type matches the exception which occurred. If no match is found for the exception, the generic except block is executed. When exception occurs in the try block, the else block will not be executed.
  • An except clause may name multiple exceptions as a parenthesized tuple, example:
... except (RuntimeError, TypeError, NameError):
...       // statement block


Example: Program to display contents of file

try:
          fs = open(“f1.txt”,”r”)
except IOError:
          print(“Unable to open file for reading”)
except:
          print(“Unknown error”)
else:
          while(True):
                    line = fs.readline()
                    If not line:
break
print(line)
finally:
          fs.close()




Raising Exceptions
The raise statement allows the programmer to force a specified exception to occur. The general syntax for raising exception:
raise [Exception [, args [, traceback]]]
Here, Exception is the type of exception (for example, NameError) and argument is a value for the exception argument and traceback is the object to be used for the exception. argument and traceback are optional values. Example –
if (level < 1):
          raise(“InvalidLevel”, level)


User-Defined Exceptions
Python also allows users to create their own exceptions by deriving classes from the standard built-in exceptions. This is used to display more specific information when an exception is caught. In the following example, In the try block, the user-defined exception is raised and caught in the except block. The variable e is used to create an instance of the class Networkerror.

class Networkerror(RuntimeError):
          def __init__(self, arg):
                   self.args = arg

Once the above class is defined, the exception can be raised as below:
try:
          raise Networkerror("Bad hostname")
except Networkerror,e:
          print e.args


No comments:

Post a Comment

Don't be a silent reader...
Leave your comments...

Anu