CHAP. 1:: Exception Handling in Python

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 42

CHAP.

1 :

EXCEPTION HANDLING IN
PYTHON
Exception or ERROR

Error is a abnormal condition


whenever it occurs execution of the
program is stopped.

An error is a term used to describe


any issue that arises unexpectedly that
cause a computer to not function properly.
Computers can encounter either software
errors or hardware errors.
ERRORS

Errors are mainly classified into following types.



1. Syntax Errors

2. Semantic Errors

3. TypeErrors

4. Run Time Errors.

5. Logical Errors.
1. Syntax Errors

Syntax errors refer to formal


rules governing the construction of valid
statements in a language.

Syntax errors occur when rules


of a programming language are misused
i.e., when a grammatical rule of the
language is violated.
1. Syntax Errors

For instance in the following program


segment,
def main() : (Colon) Missing
a=10
b=3
print(“ Sum is “,a+b

) Missing
2. Semantic Errors
Semantics error occur when statements
are not meaningful
Semantics refers to the set of rules
which give the meaning of the
statement.
For example,
Rama plays Guitar
This statement is syntactically
and semantically correct and it has
some meaning.
2. Semantic Errors
See the following statement,
Guitar plays Rama
is syntactically correct (syntax is correct) but
semantically incorrect. Similarly, there are
semantics rules of programming language,
violation of which results in semantical
errors.
X*Y=Z
will result in semantical error as
expression can not ancome on the left side
of an assignment statement.
3. Type Error
Data in Pythpn has an associated data
type. The value 7, for instance, is an
integer and ‘a’ is a character constant
“Hi” is a string. If a function is given
wrong type of data, then Type Error is
assigned by compiler
For Example :
>>a=“Hi”;
>>a**2
This will
result in
3. Type Error
4. Run Time Errors.
A Run time error is that during
occurs
execution of the program.It
because is of some illegal caused
place. operation taking
For example
1.If a program is trying to open a file which
does not exists or it could not be
opened(meaning file is corrupted), results
into an execution error.
2.An expression is trying to divide a number
by zero are RUN TIME ERRORS.
5. Logical Errors.
• A Logical Error is that error which is
causes a program to produce incorrect
or undesired output.
for instance,
ctr=1;
while(ctr>10)
print(n *ctr)
ctr=ctr+1;
Exceptions
Exceptions
What is an exception?

Even if a statement or expression is


syntactically correct, it may cause an error
when an attempt is made to execute it.
Errors detected during execution are
called exceptions
Exceptions

For Example
Built-in exceptions
Commonly occurring exceptions defined
in the compiler/interpreter.
Built-in exceptions in Python

Syntax Error:
It is raised when there is an error in the syntax of
the Python code.

Keyboard Interrupt:
It is raised when the user accidentally hits the
Delete or Esc key while executing a program due to
which the normal flow of the program is interrupted.
FileNotFound Error
If the file cannot be found.

Module not found error


If python cannot find the module.

ValueError
Raised when a built-in operation or function
receives an argument that has the right type but
an inappropriate value.
EOF Error:
It is raised when the end of file condition is
reached without reading any data by input().

Zero Division Error:


It is raised when the denominator in a
division operation is zero.

Index Error:
It is raised when the index or subscript in
a sequence is out of range.

Name Error:
It is raised when a local or global variable
name is not defined.
Indentation Error:
It is raised due to incorrect indentation in
the program code.

Type Error:
It is raised when an operator is supplied
with a value of incorrect data type.

Over Flow Error:


It is raised when the result of a
calculation exceeds the maximum limit for
numeric data type
Raising Exceptions:
 Each time an error is detected in a program, the Python
interpreter raises (throws) an exception.

 Once an exception is raised, no further statement in the


current block of code is executed which means interrupting
the normal flow execution of program and jumping to that
part of the program (exception handler code) which is written
to handle such exceptional situations.

 Programmers can also forcefully raise exceptions in a program


using the raise and assert statements.
The raise Statement
 used to throw an exception

Syntax:
raise exception-name[(optional argument)]

 argument is generally a string that is displayed when


the exception is raised

 The error detected may be a built-in exception or


may be a user-defined one
Examples
The assert Statement
 is used to test an expression in the program code.

 If the result after testing comes false, then the exception is


raised.

 This statement is generally used in the beginning of the


function or after a function call to check for valid input.

 The syntax for assert statement is:

assert Expression[,arguments]
 Python evaluates the expression given immediately after the
assert keyword. If this expression is false, an AssertionError
exception is raised which can be handled like any other
exception.
 Ex. :
print("use of assert statement")
def negativecheck(number):
assert(number>=0), "OOPS... Negative Number“
print(number*number)
print (negativecheck(100))
print (negativecheck(-350))
Handling Exceptions
 Each and every exception has to be handled by the
programmer to avoid the program from crashing
abruptly.

 This is done by writing additional code in a program


to give proper messages or instructions to the user
on encountering an exception. This process is
known as exception handling.
Need for Exception Handling
It helps in capturing runtime errors and helps us to avoid the program getting
crashed.

 Important points regarding Exceptions and their handling:


 Python categorizes exceptions into distinct types so that specific
exception handlers can be created for each type.

 Exception handlers separate the main logic of the program from the
error detection and correction code.

 The compiler or interpreter keeps track of the exact position where


the error has occurred.

 Exception handling can be done for both user-defined and built-in


exceptions.
Process of Handling Exception
 Python interpreter creates an object called the exception object.

 The object is handed over to the runtime system so that it can find an
appropriate code to handle this particular exception.

 This process of creating an exception object and handing it over to the runtime
system is called throwing an exception.

 When an exception arises it will search for exception handler.

 The process of executing a suitable handler is known as catching the exception.

 If the runtime system is not able to find an appropriate exception after


searching all the methods then the program execution stops.
Catching Exceptions
 An exception is said to be caught when a code that is
designed to handle a particular exception is executed.

 suspicious lines of codes are put inside a try block.

 Every try block is followed by an except block.

 The appropriate code to handle each of the possible


exceptions are written inside the except clause.
Example for try ..except
try...except…else clause

 An except block will be executed only if some exception is


raised in the try block.
 If there is no error then none of the except blocks will be
executed.
Finally clause:
 The try statement in Python can also have an optional
finally clause.

 The statements inside the finally block are always


executed regardless of whether an exception has
occurred in the try block or not.

 It is a common practice to use finally clause while


working with files to ensure that the file object is closed.

 If used, finally should always be placed at the end of try


clause, after all except blocks and the else block.
Recovering and continuing with finally clause:

 If an error has been detected in the try block


and the exception has been thrown, the
appropriate except block will be executed to
handle the error.

 But if the exception is not handled by any of


the except clauses, then it is re-raised after
the execution of the finally block.
 While executing the above code, if we enter a non-
numeric data as input, the finally block will be
executed.

 So, the message “OVER AND OUT” will be displayed.


Thereafter the exception for which handler is not
present will be re-raised.

 That is, unlike except, execution of the finally clause


does not terminate the exception. Rather, the
exception continues to be raised after execution of
finally.
output
Recap :
 we put a piece of code where there are possibilities of
errors or exceptions to occur inside a try block.

 Inside each except clause we define handler codes to


handle the matching exception raised in the try block.

 The optional else clause contains codes to be executed if


no exception occurs.

 The optional finally block contains codes to be executed


irrespective of whether an exception occurs or not.

You might also like