Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 10

ERRORS AND EXCEPTIONS

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.

2. List of Standard Exceptions

S.No. Exception Name & Description

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.

Example program for try with except statement


try:
n=int(input("Enter the number: "))
except ValueError:

3
print("You have entered wrong data")
else:
print("you have entered ",n)

Example program for try with except statement


try:
f1=open("sample.txt","r")
f1.read()
except IOError:
print("File does not exist")
else:
print("Successfully done")

Example program for single try with multiple except statements


try:
a=int(input("Enter the value of a: "))
b=int(input("Enter the value of b: "))
c =a/b
except ValueError:
print("You have entered wrong data")
except ZeroDivisionError:
print("Divide by Zero Error")
else:
print("Result: ",c)

3.1. Except with no Exception

Except statement can also be used without specifying Exception.

Syntax:
try:
code
except:
code to be executed in case exception occurs.
else:
code to be executed in case exception does not occur.

Example program for try with no exception


try:
n=int(input("Enter the number"))
except:

4
print("entered wrong data")
else:
print("you have entered ",n)

3.2.Declaring Multiple Exceptions

Multiple Exceptions can be declared using the same except statement

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.

Example program for multiple exceptions


try:
a=int(input("Enter the value of a: "))
b=int(input("Enter the value of b: "))
c =a/b
except (ValueError,ZeroDivisionError):
print("Multiple Exceptions")
else:
print("Result: ",c)

3.3. The try-finally Clause


You can use a finally: block along with a try: block. The finally block is a place to put any
code that must execute, whether the try-block raised an exception or not.
Syntax:
try:
code
except Exception:
execute code
finally:
code which must be executed

Example program for try-finally block


try:
age=int(input("Enter your age: "))
except ValueError:

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

Example program for creating and importing a module

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)

Using from.. import statement:


from..import statement is used to import particular attribute from a module. In case you
do not want whole of the module to be imported then you can use from..import statement.

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)

Built in Modules in Python:


 There are many built in modules in Python. Some of them are as follows:
math, random , threading , collections , os , mailbox , string , time.
 Each module has a number of built in functions which can be used to perform various
functions.
1. math module
Functions:

Function Description

ceil(n) Returns the next integer number of the given number

sqrt(n) Returns the Square root of the given number.

exp(n) Returns the natural logarithm e raised to the given number

floor(n) Returns the previous integer number of the given number.

log(n,baseto) Returns the natural logarithm of the number.

pow(baseto, exp) Returns baseto raised to the exp power.

sin(n) Returns sine of the given radian.

cos(n) Returns cosine of the given radian.

7
tan(n) Returns tangent of the given radian.

Example of math module:


import math
print math.sqrt(9)
print math.exp(3.0)
print math.log(2.0)
print math.pow(2.0,3.0)
print math.sin(0)
print math.cos(0)
print math.tan(45)

Constants:
The math module provides two constants for mathematical Operations:

Constants Descriptions

Pi Returns constant π = 3.14159...

E Returns constant e= 2.71828...


Example
import math
print math.pi
print math.e

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

What is the use of _init_.py file?


_init_.py file is used to make directory as a Python package directory.

Example on How to Create a Python Package

Step 1: Create a folder name MyMath in D: drive


Step 2: Inside MyMath directory create _init_.py file. Just create an empty file
Step 3: Create a folder name Add inside MyMath. Inside Add folder create file named
addition.py
addition.py
def add_fun(a,b):
return a+b
Step 4: Create a folder name Sub inside MyMath. Inside Sub folder create file named
subtraction.py
subtraction.py
def sub_fun(a,b):
return a-b

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

You might also like