Tuesday, 2 August 2016

Exceptions handling in python with Examples

Exceptions handling in python with Examples:
What is an exception?
In this post I am trying to explain how the exceptions got
Here I am giving definition to the exception. An event which is got occurred during the execution of a program which disturbs the normal flow of our application is known as exception. When an exception occurs, it causes the current process to stop and passes it to the calling process until it is handled. If we cannot handled it properly, our application will crash. To avoid these types of problems we need to catch them and handle them properly, then our application will not crash and cannot got interrupted in middle.
Catching Exceptions in Python:
As of we know that the exceptions can be handled using a try statement. A code segment which can raise exception is placed inside the try and the code that handles exception is written in except.
In python we have two features available to handle the exceptions
·       Assertions
·       Exception Handling
Here I am Listing Standard Exceptions that can arise in python.
Name of the Exception
This is the base class for all exceptions
StopIteration  Exception
This is raised when the next() method of an iterator does not point to any object.
SystemExit Exception
This is raised by the sys.exit() function.
StandardError Exception
This is raised base class for all built-in exceptions except StopIteration and SystemExit.
ArithmeticError Exception
This is raised base class for all errors that occur for numeric calculation.
OverflowError Exception
This is raised when a calculation exceeds maximum limit for a numeric type.
FloatingPointError Exception
This is raised when a floating point calculation fails.
ZeroDivisonError Exception
This is raised when division or modulo by zero takes place for all numeric types.
AssertionError Exception
This is raised in case of failure of the Assert statement.
AttributeError Exception
This is raised in case of failure of attribute reference or assignment.
EOFError Exception
This is raised when there is no input from either the raw_input() or input() function and the end of file is reached.
ImportError Exception
This is raised when an import statement fails.
KeyboardInterrupt Exception
This is raised when the user interrupts program execution, usually by pressing Ctrl+c.
LookupError Exception
This is raised when the base class for all lookup errors.
KeyError Exception
This is raised when an index is not found in a sequence.
This is raised when the specified key is not found in the dictionary.
NameError Exception
This is raised when an identifier is not found in the local or global namespace.
This is raised when trying to access a local variable in a function or method but no value has been assigned to it.
This is raised, Base class for all exceptions that occur outside the Python environment.
IOError Exception
 IOError Exception
This is raised when an input/ output operation fails, such as the print statement or the open() function when trying to open a file that does not exist.
Raised for operating system-related errors.
IndentationError IOError Exception
This is raised when there is an error in Python syntax.
This is raised when indentation is not specified properly.
SystemError Exception
This is raised when the interpreter finds an internal problem, but when this error is encountered the Python interpreter does not exit.
SystemExit Exception
This is raised when Python interpreter is quit by using the sys.exit() function. If not handled in the code, causes the interpreter to exit.
ValueError Exception
This is raised when the built-in function for a data type has the valid type of arguments, but the arguments have invalid values specified.
RuntimeError Exception
This is raised when a generated error does not fall into any category.
NotImplementedError Exception
This is raised when an abstract method that needs to be implemented in an inherited class is not actually implemented.

Assertions in Python along with examples
Basically the assertions are used at the time of our unit testing of the program. In python assert keyword is the statement that is used to validate the inputs and after a function call to check for valid output.
Usage of the assert Statement
When python finds assert statement in the code it evaluates the accompanying expression, which is hopefully true. If the expression is false, Python raises anAssertionError exception.
The syntax for assert is as shown below.
 assert Expression[,Args]
If it fails, AssertionError exceptions can be caught and handled like any other exception using the try-except statement, but if not handled, they will terminate the program and produce a traceback.

Here is the sample Example that shows how assertions are work :

Here is a function that takes val1, val2 &count as arguments, in the
def get_Vals(val1, val2, count):
assert count < 0
assert val1 >= -30.0 and val1 <= 30.0
assert val2 >= -60.0 and val2 <= 6.0
# statments.....
Handling an exception in python: 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. The except statement is followed by the try, which handles the problems that are raised in the try block.

Syntax The below is simple syntax of try....except...else blocks

# your statements .............
except ExceptionI:
except ExceptionII:
# your statments.............
# your statments
# your statments..............
Here I am providing some Finger tips to memorize:

• 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.
• To handle any exception we can also provide a generic except clause.
• Else clause will come after the except clauses
• The else-block is a good place for code that does not need the try: block's protection.

Example -1

This example opens a file, writes content in the, file, see carefully how we have to handle the exceptions
f = open("D:\\Temp\\BoundingBox1.txt", "w")
f.write ("min_X, min_Y, max_X, max_Y")
print "Error: can\'t find file or read data"
f.write("\n")except IOError:
print "unable to write data into the file"
Example-2 In this example I am trying to open the file which not having any permissions, So in this case we can get the exception and we need to handle it.
with open(filename, "r") as ins:
for line in ins:except IOError:
print "Error: can\'t find file or read data"
#our statments
print "Unable to open the file, because of no permissions"

No comments: