Professional Documents
Culture Documents
Psp-Exception Handling
Psp-Exception Handling
Errors are normally referred as bugs in the program. The process of finding and eliminating
errors is called debugging.
There are two types of errors:
1. Syntax errors: The python finds the syntax errors when it parses the source program.
Common syntax errors:
Putting a keyword at wrong place
Misspelling the keyword
Incorrect indentation
Forgetting the symbols such as comma, brackets, quotes
2. Runtime errors: The program may exit unexpectedly during execution, if it encounters a
runtime error. The runtime errors will occur due to logical mistakes
Common runtime errors:
Trying to access a file which does not exist
Performing the operation of incompatible type element
Using an identifier which is not defined
Division by zero
These types of error are handled using exception handling mechanism.
1. What is Exception?
Runtime anomalies or error is called exception
Exception is an abnormal condition, which occurs during the execution of a
program that disrupts the normal flow of the program.
1 Exception
Base class for all exceptions
2 StandardError
Base class for all built-in exceptions except StopIteration and SystemExit.
3 ArithmeticError
Base class for all errors that occur for numeric calculation.
4 OverflowError
Raised when a calculation exceeds maximum limit for a numeric type.
1
5 FloatingPointError
Raised when a floating point calculation fails.
6 ZeroDivisionError
Raised when division or modulo by zero takes place for all numeric types.
7 AttributeError
Raised in case of failure of attribute reference or assignment.
8 EOFError
Raised when there is no input from either the raw_input() or input() function and the
end of file is reached.
9 ImportError
Raised when an import statement fails.
10 KeyboardInterrupt
Raised when the user interrupts program execution, usually by pressing Ctrl+c.
11 IndexError
Raised when an index is not found in a sequence.
12 KeyError
Raised when the specified key is not found in the dictionary.
13 NameError
Raised when an identifier is not found in the local or global namespace.
14 UnboundLocalError
Raised when trying to access a local variable in a function or method but no value has
been assigned to it.
15 IOError
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.
16 SyntaxError
Raised when there is an error in Python syntax.
17 IndentationError
Raised when indentation is not specified properly.
18 SystemError
Raised when the interpreter finds an internal problem, but when this error is
2
encountered the Python interpreter does not exit.
19 SystemExit
Raised when Python interpreter is quit by using the sys.exit() function. If not handled in
the code, causes the interpreter to exit.
20 TypeError
Raised when an operation or function is attempted that is invalid for the specified data
type.
21 ValueError
Raised when the built-in function for a data type has the valid type of arguments, but
the arguments have invalid values specified.
22 RuntimeError
Raised when a generated error does not fall into any category.
3. Exception Handling
To handle the exception, enclose the code which raises an exception inside the try
block. The try block is followed except statement which handles the exception. If there is no
exception the else block statements get executed.
Syntax:
try:
malicious code
except Exception1:
execute code
except Exception2:
execute code
....
....
except ExceptionN:
execute code
else:
In case of no exception, execute the else block code.
3
print("You have entered wrong data")
else:
print("you have entered ",n)
Syntax:
try:
code
except:
code to be executed in case exception occurs.
else:
code to be executed in case exception does not occur.
4
print("entered wrong data")
else:
print("you have entered ",n)
Syntax:
try:
code
except (Exception1,Exception2,Exception3,..,ExceptionN )
execute this code in case any Exception of these occur.
else:
execute code in case no exception occurred.
5
print("Invalid age")
finally:
print("Finally Block")
MODULES
What is python module?
A module is simply a file containing Python statements and definitions.
Advantage of modules
1) Reusability: Module can be used in some other python code. Hence it provides the
facility of code reusability.
2) Categorization: Similar type of attributes can be placed in one module.
Importing a Module
"import" statement can be used to import a module.
Syntax:
import module-name
addition.py
# Module named addition is created
def add(a,b):
c=a+b
print c
sample.py
# Program for importing a module
import addition
addition.add(10,20)
addition.add(30,40)
Syntax:
from <module_name> import <attribute1,attribute2,attribute3,...attributen>
6
Example program
# creating module
area.py
def circle(r):
print 3.14*r*r
def square(a):
print a*a
def rectangle(l,b):
print l*b
area1.py
# importing modules
from area import square,rectangle
square(10)
rectangle(2,5)
Function Description
7
tan(n) Returns tangent of the given radian.
Constants:
The math module provides two constants for mathematical Operations:
Constants Descriptions
2. random module
The random module is used to generate the random numbers. It provides the following two
built in functions:
Function Description
random() It returns a random number between 0.0 and 1.0 where 1.0 is exclusive.
randint(x,y) It returns a random number between x and y where both the numbers are
inclusive.
Example:
import random
print random.random()
print random.randint(2,8)
8
PACKAGES
What is Package?
Packages are namespaces which contain sub packages and modules. They are simply
directories.
Steps to Create a Package
1. Create a directory and give it your package's name.
2. Put your modules and subdirectories (ie., subpackages) in it.
3. Create a _init_.py file in the directory
The _init_.py file is necessary because with this file, Python will know that this directory is a
Python package directory.
Accessing Package
To access the package, subpackages and modules, use import statement.
import package-name
import package-name.subpackage-name
import package-name.module-name
Step 5: Create a folder name Mul inside MyMath. Inside Mul folder create file named
multiplication.py
multiplication.py
def mul_fun(a,b):
return a*b
Step 6: Create a folder name Div inside MyMath. Inside Div folder create file named division.py
9
division.py
def div_fun(a,b):
return a/b
step 7: Create a python program to access MyMath package
package-test.py
import MyMath.Add.addition
import MyMath.Sub.subtraction
import MyMath.Mul.multiplication
import MyMath.Div.division
print("Addition :",MyMath.Add.addition.add_fun(10,20))
print("Subtraction:",MyMath.Sub.subtraction.sub_fun(10,20))
print("Multiplication:",MyMath.Mul.multiplication.mul_fun(10,20))
print("Division:",MyMath.Div.division.div_fun(10,2))
10