0% found this document useful (0 votes)
22 views47 pages

Python Exception Handling Guide

The document provides an overview of exception handling in Python, explaining the types of errors (syntax, runtime, and logical) and how exceptions are raised and handled. It details the use of try-except blocks, the raising of exceptions, and the importance of handling exceptions to prevent program crashes. Additionally, it covers the use of else and finally clauses in exception handling for better control flow.

Uploaded by

mrinmoydas20007
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views47 pages

Python Exception Handling Guide

The document provides an overview of exception handling in Python, explaining the types of errors (syntax, runtime, and logical) and how exceptions are raised and handled. It details the use of try-except blocks, the raising of exceptions, and the importance of handling exceptions to prevent program crashes. Additionally, it covers the use of else and finally clauses in exception handling for better control flow.

Uploaded by

mrinmoydas20007
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

EXCEPTION HANDLING

IN PYTHON

1
2

LEARNING
OUTCOMES
3

● while executing a Python program, the


program does not execute at all or the
program executes but generates
unexpected output or behaves
abnormally.
INTRODUCTI
● These occur when there are syntax
ON errors, runtime errors or logical errors in
the code.
● In Python, exceptions are errors that get
triggered automatically.
4

● Syntax errors are detected when we have


not followed the rules of the particular
programming language while writing a
program.
● These errors are also known as parsing
SYNTAX
errors.
ERRORS
● On encountering a syntax error, the
interpreter does not execute the program
unless we rectify the errors, save and rerun
the program.
5
6

● Syntax error is reported by the Python


interpreter giving a brief explanation
SYNTAX
about the error and a suggestion to rectify
ERROR it.
7
8

● Even if a statement or expression is


syntactically correct, there might arise an
error during its execution.
● For example, trying to open a file that does
EXCEPTIONS not exist, division by zero and so on.
● Such types of errors might disrupt the
normal execution of the program and are
called exceptions.
9

● An exception is a Python object that


represents an error.
● When an error occurs during the execution
of a program, an exception is said to have
EXCEPTIONS been raised.
-2 ● Such an exception needs to be handled
by the programmer so that the program
does not terminate abnormally.
10

BUILT-IN
EXCEPTIONS
11
12

● A programmer can also create custom


USER-DEFIN exceptions to suit one’s requirements.
ED ● These are called user-defined
EXCEPTIONS exceptions.
13

● Each time an error is detected in a program, the


Python interpreter raises (throws) an exception.
● Exception handlers are designed to execute
when a specific exception is raised.
● Programmers can also forcefully raise
exceptions in a program using the raise and
RAISING assert statements.
Once an exception is raised, no further statement
EXCEPTIONS ●
in the current block of code is executed.
● So, raising an exception involves 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.
14

The raise
Statement
15
16

● This is a structured block of text that


contains information about the sequence
STACK of function calls that have been made in
TRACEBACK the branch of execution of code in which
the exception was raised.
17
18

● An assert statement in Python is used to


test an expression in the program code.
● If the result after testing comes false, then
the exception is raised.
The assert
Statement ● 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:
19

● On encountering an assert statement,


Python evaluates the expression given
immediately after the assert keyword.
Assert
continued…. ● If this expression is false, an
AssertionError exception is raised which
can be handled like any other exception.
ASSERT EXAMPLE

20
21
22

● Each and every exception has to be


handled by the programmer to avoid the
program from crashing abruptly.

HANDLING ● This is done by writing additional code in


EXCEPTIONS a program to give proper messages or
instructions to the user on encountering
an exception. This process is known as
exception handling.
23

● Exception handling is being used not only


in Python programming but in most
programming languages like C++, Java,
Need for Ruby, etc.
Exception ● It is a useful technique that helps in
Handling capturing runtime errors and handling
them so as to avoid the program getting
crashed.
24

● Python categorises exceptions into distinct types so


that specific exception handlers (code to handle that
particular exception) can be created for each type.
● Exception handlers separate the main logic of the
program from the error detection and correction code.
IMPORTANT ● The segment of code where there is any possibility of
POINTS error or exception, is placed inside one block.
REGARDING ● The code to be executed in case the exception has
EXCEPTIONS occurred, is placed inside another block.
These statements for detection and reporting the
AND THEIR ●
exception do not affect the main logic of the program.
HANDLING ● 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
25

● Error occurs, Python interpreter creates an object


called the exception object.
● This object contains information about the error like
its type, file name and position in the program where the
error has occurred.
● The object is handed over to the runtime system so
Process of that it can find an appropriate code to handle this
particular exception.
Handling ● This process of creating an exception object and
Exception handing it over to the runtime system is called throwing
an exception.
● It is important to note that when an exception occurs
while executing a particular program statement, the
control jumps to an exception handler, abandoning
execution of the remaining program statements.
26

● The runtime system searches the entire program for a block of


code, called the exception handler that can handle the
raised exception.
● It first searches for the method in which the error has occurred
and the exception has been raised.
● If not found, then it searches the method from which this
Process of method (in which exception was raised) was called.

Handling ● This hierarchical search in reverse order continues till the


exception handler is found.
Exception ● This entire list of methods is known as call stack.
continued….. ● When a suitable handler is found in the call stack, it is
executed by the runtime process. This 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 in the call stack,
then the program execution stops.
27
28

● An exception is said to be caught when a code that


is designed to handle a particular exception is
executed.
● Exceptions, if any, are caught in the try block and
handled in the except block.
● While writing or debugging a program, a user
Catching might doubt an exception to occur in a
particular part of the code. Such suspicious lines
Exceptions of codes are put inside a try block.
● Every try block is followed by an except block.
● While executing the program, if an exception is
encountered, further execution of the code inside
the try block is stopped and the control is
transferred to the except block.
29

Using
try..except
block
30
31

● Sometimes, a single piece of code might


be suspected to have more than one
type of error.
● For handling such situations, we can have
multiple except blocks for a single try
block.
32

Multiple
except clause
33
34

NO ● such an exception can be handled by


HANDLER IS adding an except clause without
CREATED BY specifying any exception.
THE ● This except clause should be added as the
PROGRAMME last clause of the try..except block.
R
If the above code is executed, and the denominator entered is 0 (zero) , the handler for
ZeroDivisionError exception will be searched. Since it is not present, the last except clause (without
any specified exception) will be executed , so the message “ OOPS.....SOME EXCEPTION RAISED”
will be displayed.

35
36

● We can put an optional else clause along


with the try...except clause.
● An except block will be executed only if
some exception is raised in the try block.
try...except…
else clause ● But if there is no error then none of the
except blocks will be executed.
● In this case, the statements inside the
else clause will be executed.
37
38

● 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.
finally Clause ● 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.
39
40

● In the previous program, the message


“OVER AND OUT” will be displayed
finally Clause irrespective of whether an exception is
raised or not.
41

● If an error has been detected in the try


block and the exception has been thrown,
the appropriate except block will be
Recovering and executed to handle the error.
continuing with
finally clause ● 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.
42
43

● After execution of finally block, Python


transfers the control to a previously
entered try or to the next higher level
default exception handler.
● In such a case, the statements following
Conclusion
the finally block is executed. That is, unlike
finally block except, execution of the finally clause
does not terminate the exception.
● Rather, the exception continues to be
raised after execution of finally.
44
45
46
47

You might also like