Errors are normally referred as bugs in the program. They are almost always the fault of the programmer. The process of finding and eliminating errors is called debugging.
Errors and Exceptions AU : Jan.-18, May-19,
Dec.-19, Marks 1
Errors
are normally referred as bugs in the program. They are almost always the fault
of the programmer. The process of finding and eliminating errors is called
debugging.
There
are mainly two types of errors :
1.
Syntax errors: The python finds the syntax errors when
it parses the source program. Once it find a syntax error, the python will exit
the program without running anything. Commonly occurring syntax errors are :
(i)
Putting a keyword at wrong place
(ii)
Misspelling the keyword
(iii)
Incorrect indentation
(iv)
Forgetting the symbols such as comma, brackets, quotes
(v)
Empty block
2.
Run time errors : If a program is syntactically correct -
that is, free of syntax errors – it will be run by the python interpreter.
However, the program may exit unexpectedly during execution if it encounters a
runtime error. The run-time errors are not detected while parsing the source
program, but will occur due to some logical mistake. Examples of runtime error
are :
(i)
Trying to access the a file which does not exists
(ii)
Performing the operation of incompatible type elements
(iii)
Using an identifier which is not defined
(iv)
Division by zero Such type of errors are handled using exception handling
mechanism.
Definition
of exception : An exception is an event which occurs
during the execution of a program that interrupts the normal flow of the
program.
•
In general, when a python script encounters a situation that it cannot cope
with, it raises an exception.
•
When a python script raises an exception, it must either handle the exception
immediately otherwise it terminates and quits.
•
The exception handling mechanism using
the try...except...else blocks.
•
The suspicious code is placed in try block.
•
After try block place the except block which handles the exception elegantly.
•
If there is no exception then the else block statements get executed.
Syntax
of try...except...else
try:
write
the suspicious code here
except
Exception 1:
If
Exception 1 occurs then execute this code
except
Exception 2:
If
Exception 2 occurs then execute this code
else:
If
there is no exception then execute this code.
Example
Suppose
programmer wants some integer value and some character value is entered then
python will raise error. This scenario can be illustrated by following
screenshot
Such
situation can be gracefully handled using exception handling mechanism as
follows:
Step
1:
Create a python script as follows:
Step
2:
Now run the above code for both valid and invalid inputs.
Output(Run1:
Execution of except block)
•
A single try can have multiple except statements. We can specify standard
exception names for handling specific type of exception. For example Example
5.3.1
:
Write a python program to perform division of two numbers. Raise the
exception
if the wrong input(other than integer) is entered by the user. Also raise an exception
when divide by zero occurs,
Solution
:
try:
a
= int(input("Enter value of a: "))
b
= int(input("Enter value of b: "))
c
= a/b
except
ValueError:
print("You
have entered wrong data")
except
Zero DivisionError:
print("Divide
by Zero Error!!!")
else:
print("The
result: ",c)
Output(Run1)
Example
5.3.2 Write a program to read th contents of the file.
If the file does not exist then raise appropriate exception.
Solution
:
try
:
inFile
= open(“myfile.txt”,’rt’)
except
IOError:
print(“Error;File
Not found”)
else;
print(inFile.read())
# displaying contents of file on getting file
Output
Example
5.3.3 : Write a python program to open a file having no
write permission but trying to write the data. Handle this situation using
exception handling mechanism.
Solution
:
try:
FileObj
= open("myfile.txt","rt')
FileObj.write("This
is my data")
except
IOError:
print("Error:File
does not have write permission!!!")
else:
print("Contents
are written Successfully!!!")
Output
Standard
Exceptions in Python
Name
: Pur Purpose
1.
Exception - Base class for all exceptions
2.
ArithmeticError - Base class for all errors that occur for numeric calculation.
3.
OverflowError - Raised when a calculation exceeds maximum limit for a numeric type.
4.
Floating PointError - Raised when a floating point calculation fails.
5.
ZeroDivisionError - Raised when division or modulo by zero takes place for all
numeric types.
6.
EOFError - Raised when there is no input from either the raw_input() or input()
function and the end of file is reached.
7.
ImportError - Raised when an import statement fails.
8.
KeyboardInterrupt Raised when the user interrupts program execution, usually by
pressing Ctrl+c.
9.
NameError - Raised when an identifier is not found in the local or global
namespace.
10.
IOError - Raised when an input/ output operation fails.
11.
SystemError - Raised when the interpreter finds an internal problem, but when
this error is encountered the python interpreter does not exit.
12.
SystemExit - Raised when python interpreter is quit by using the sys.exit()
function. If not handled in the code, causes the interpreter to exit.
13.
TypeError - Raised when an operation or function is attempted that is invalid
for the specified data type.
14.
ValueError - Raised when the built-in function for a data type has the valid
type of arguments, but the arguments have invalid values specified.
15.
RuntimeError - Raised when a generated error does not fall into any category.
Use
of finally
The
finally clause will be executed at the end of the try-except block no matter
what - if there is no exception, if an exception is raised and handled, if an
exception is raised and not handled, and even if we exit the block using break,
continue or return. We can use the finally clause for cleanup code that we
always want to be executed.
For
example :
try:
age
= int(input("Enter your age'))
except
ValueError:
print("Invalid
age")
else:
print("Your
age is: ",age)
finally:
print("Good
Bye")
Output(Run1) Output(Run2)
Review Questions
1. Appraise use of try block and except block in Python with
syntax AU: Jan.-18, Marks 6
2. Describe how exceptions are handled in Python with necessary
examples AU : May-19, Marks 8,
Dec.-19, Marks 16
3. What are exceptions ? Explain the methods to handle them with
example.
AU : Dec.-19, Marks 8
Problem Solving and Python Programming: UNIT V: Files, Modules, Packages : Tag: Engineering Python : Files | Python Programming - Errors and Exceptions
Problem Solving and Python Programming
GE3151 1st Semester | 2021 Regulation | 1st Semester Common to all Dept 2021 Regulation