Archive | Python Exception RSS feed for this section

Error and Exception

26 Sep

An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program’s instructions.

ArithmeticError:
-> Parent for exceptions that python raises for various arithmetic errors.
FloatingPointError:
-> Raised when floating point operation fails.
OverflowError:
-> Raised when the result of an arithmetic operation is too large to be represented.
ZeroDivisionError:
-> Raised when second argument of a normal or modular division is zero.

AssertionError:
-> Raised When assert statement fails.

AttributeError:
-> Raised when attribute reference or assignment fails.
-> If python does not support attribute reference or attribute assignments, python raises a TypeError exception instead.

EnvironmentError:
-> Raised an exceptions that occur outside python.
IOError :
-> Raised when I/O operation fails for an I/O related reason. Eg “File not found” or “disk full”.
OSError:
-> Raised when OS related error occurs.
-> A numeric error code usually accompanies this exception.
WindowsError:
-> Raised when windows specific error occurs.

EOFError:
-> Raised when input() or raw_input() encounters EOF condition without reading data.

ImportError:
-> Raised when import fails to find a module or when from-import fails to find a name.

KeyboardInterrupt:
-> Raised when user presses the interrupt key.
-> Python regularly checks for interrupts during program execution.
-> Python also raises this exception if the user types an interrupts while
input() or raw_input() is waiting for input.

LookupError:
-> Parent for exceptions that python raises when a dictionary key or sequence(string, list or tuple) index is invalid.
IndexError:
-> Raised when sequence index is out of range.
-> If an index is not a plain integer, python raises a TypeError exception.
KeyError:
-> Raised when python cant find a dictionary key.

MemoryError:
-> Raised when an operation runs out of memory but the progrm may still be rescued by deleting some objects.

NameError:
-> Raised when cant find a local or global name.
-> The exception argument is a string that indicates the missing name.
UnboundLocalError:
-> Raised when referenced a local variable in a function or method, but no value has been assigned to that variable.

RuntimeError:
-> Raised when python detects a generic error that doesn’t fall in any of the other categories.
-> Exception argument is a string that indicates what went wrong.
-> Python rarely raises this catch-all exception.
NotImplementedError:
-> Raised when invoke a method that hasn’t been implemented.

SyntaxError:
-> Raised when syntax error detects.
-> This exception may occur in an import statement, in an exec statement, in an eval() or input() call when reading script initially or when reading standard input.
TabError:
-> Raised when you use the -tt command-line option with a program that uses tabs          and spaces inconsistently.
IndentationError:
-> Raised when program breaks indentation rule.

SystemError:
-> Raised when python encounters an internal error.
-> A generic error that is raised when something goes wrong with the Python interpreter.

TypeError:
-> This error is raised when attempting to perform an operation on an incorrect object type.

ValueError:
-> Raised when pass a built-in operation or function argument that has right type but an inappropriate value.
UnicodeError:
-> Raised when unicode related encoding or decoding error occurs.

sys.exc_info()
-> Function returns the type, value and traceback of the current exception in tuple format
(type, value, traceback)
where,
type – type of exception that is raised.
value – exception’s argument or second argument of the raise statement.
tracebaack – line number where error occured. Don’t assign traceback to a local variable in function handling as it will lead to circular reference.

Eg:
import sys
try:
f=open(‘xxx.txt’,”r”)
except:
true, value = sys.exc_info()[:2]
print (“type”,true) # type: exceptions.IOError
print (“value”,value) # value: [Errno 2] No such file or directory: ‘xxx.txt’

Ignoring an Exception:
-> To ignore use a pass statement in an except clause.
Eg:

import os
try:
os.remove(“E:\\temp\\log.tmp”)
except:
pass

Getting Exception’s Argument:
-> Exception have an associated value known as its argument.
-> Argument type and value depend on the exception type.
-> OS errors like IOError have an extra attribute that gives OS information (i.e Error number or file name).
-> By using dir() function , we can list an argument’s attributes.
Eg:
except IOError, e:
print (“dir…”,dir(e))                         # o/p:  dir… [‘args’,’errno’,’filename’,’strerror’]
print (“e.args..”,e.args)                    # o/p:  e.args.. (2,’No such file or directory’)
print (“e.errno..”,e.errno)               # o/p:  e.errno.. 2
print (“e.filename..”,e.filename)   # o/p:  e.filename.. xxx.txt
print (“e.strerror..”,e.strerror)      # o/p:  e.strerror.. No such file or directory

-> this variable e available after except block finishes.
-> We can print e using str(e) for formated string.
-> This ‘e’ variable is an instance of class, so we can retrieve its class attributes. Eg: e.__class__.__doc__

Handling All Exceptions:
-> To catch all exceptions, we need to specify clause with no exception name or argument name.
Eg:
try:
statements
except:
handling statements

-> But it is poor choice because it catches any exception than ones that we interested.
-> To catch all build-in exceptions, we can use like below,
try:
statements
except StandardError:
except_block
——————————————————–
Else clause:
-> This is to run set of code when no exception detected.
-> else block will be executed only when no exception observed in try block.)
-> else clause must follow the last except clause.
-> When exception occured in try blcok, else block will not be executed.
try:
f=open(‘xxx.txt’,’r’)
except:
print (“File cant open”)
else:
s=f.readlines()
print s
f.close()
——————————————————–
Handling Multiple Exceptions:
-> It can be handled in two methods. The target argument is an optional variable.
1. Use multiple except clauses.
eg:

except TypeError, e:
except_block
except ZerodivisionError, e:
except_block
-> Python examines each except clause from first to last to determine matching type exception.
2. Using single except clause to catch multiple exceptions types.
eg: except (TypeError, ZeroDivisionError) , e:
except_block
-> It should be specific clause first and followed by catch all excetion clause.
——————————————————–
Cleanup code (finally):
-> finally clause will be executed regardless of whether raises an exception to perform cleanup action.
-> It does not catch any exceptions.
-> If exception occurred in try_block, rest of the try_block will be skipped and finally_block will be executed then exception will be raised.
-> We cannot add ‘else’ clause to a try-finally statement.
-> If it encounter control flow statement such as break or return, then control goes to finally_block.
-> finally clause and an except clause cant appear together within a single try statement.
-> Generally try-finally statement nested in an try-except statement to handle the exception raised in the try-finally statement.
eg:
try:
statements
try:
statements
finally:
statements
except:
statements
——————————————————–
Raising an exception:
-> We can use raise statement to force a specified exception to occur.
Eg:
-> raise ex
-> raise ex,arg
-> raise ex, (arg1,arg2,..)
Here, ex is an exception type. arg, arg1, arg2 are expressions.
-> It raises exception ex with optional arguments that give specific details about the exception.
-> Argument can be a single value or tuple of values.
-> If argument is omitted, the exception argument defaults to None.
-> Type raise with no arguments to raise the current exception again. If there is no current exception to raise,
python raises a TypeError.
-> raise statement takes an optional third argument ‘traceback’ which is traceback object.
——————————————————–
User-Defined Exceptions
-> Exceptions can be string, classes or instances.
Eg:
class MyError(Exception):
def __init__(self,arg):
self.arg = arg
def__str__(self):
return str(self.arg)

raise MyError
raise MyError()
raise MyError, “testing”
raise MyError(“testing”)

Here, It creates new exception class, ‘MyError’ which inherits from exception.
__str__() method creates the nicely formatted string form of arg.
‘MyError’ is an exception type and ‘arg’ is a variable name.

eg:
class mine():

def __init__(self, height, width, msg):
self.arg = (msg, height, width)
self.msg = msg
self.height = height
self.width = width
def __str__(self):
return str(self.arg)

raise mine (“2”, “3”, “4”)
——————————————————–
Assertion:
-> It is debugging tool to print diagnostic information while programs runs.
-> Assert statement contains boolean expression.That if it fails, indicates an error.
-> If expression evaluates to false, python raises an AssertionError exception.
eg :
assert expr [,arg]
Where,
– expr is a test(boolean) expression that evaluates to true or false.
– arg is expression. If arg is omitted, defaults to None.
– If expr is false, python raises an AssertionError exception with optional argument arg.
– If expr is true, python takes no action.

-> Python translate the assert statement internally to this code.
if __debug__:
if not expr:
raise AssertionError, arg
Here,
– __debug__ is a built-in read only variable that is 1 (true) by default.
– To change __debug__ to 0(false), specify the -O or the -OO(uppercase ohs) command-line option to start python in optimized mode and ignore assertions.
eg:   python -O script.py
Where, script.py contains assert statements.
– Or By setting Python environment variable PYTHONOPTIMIZE to 0 (for diable) or 1 (for enable) assertions.
-> Assertions recommended to use for debugging purposes only. Not for tasks such as checking the validity.
——————————————————–
Continue reading