0% found this document useful (0 votes)
30 views

Exception Handling 5

The document discusses Python multithreading and exception handling. It describes common exceptions like ZeroDivisionError and NameError. It explains how to use try, except, else and finally blocks to handle exceptions in Python. It also discusses threading in Python using the Thread class, and how to create and synchronize threads. Key points covered include using run(), start() and join() methods of Thread class, and using locks or semaphores to synchronize access to shared resources across threads.

Uploaded by

patilpatil
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Exception Handling 5

The document discusses Python multithreading and exception handling. It describes common exceptions like ZeroDivisionError and NameError. It explains how to use try, except, else and finally blocks to handle exceptions in Python. It also discusses threading in Python using the Thread class, and how to create and synchronize threads. Key points covered include using run(), start() and join() methods of Thread class, and using locks or semaphores to synchronize access to shared resources across threads.

Uploaded by

patilpatil
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Python Multithreading and

Exception Handling
• Exception Handling
• An exception can be defined as an unusual condition in a program
resulting in the interruption in the flow of the program.
• Whenever an exception occurs, the program stops the execution,
and thus the further code is not executed. Therefore, an exception
is the run-time errors that are unable to handle to Python script. An
exception is a Python object that represents an error
• Python provides a way to handle the exception so that the code can
be executed without any interruption. If we do not handle the
exception, the interpreter doesn't execute all the code that exists
after the exception.
• Handling of exception ensures that the flow of the program does
not get interrupted when an exception occurs which is done by
trapping run-time errors. Handling of exceptions results in the
execution of all the statements in the program.
• Common Exceptions
• Python provides the number of built-in exceptions, but here we are
describing the common standard exceptions. A list of common
exceptions that can be thrown from a standard Python program is
given below.
• ZeroDivisionError: Occurs when a number is divided by zero.
• NameError: It occurs when a name is not found. It may be local or
global.
• IndentationError: If incorrect indentation is given.
• IOError: It occurs when Input Output operation fails.
• EOFError: It occurs when the end of the file is reached, and yet
operations are being performed.
• The try-expect statement
• If the Python program contains suspicious code that may throw the
exception, we must place that code in the try block. The try block
must be followed with the except statement, which contains a
block of code that will be executed if there is some exception in the
try block.
Syntax
try:
#block of code

except Exception1:
#block of code

except Exception2:
#block of code

#other code
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
except:
print("Can't divide with zero")
The syntax to use the else statement with the try-except statement is
given below.
try:
#block of code
except Exception1:
#block of code
else:
#this code executes
if no except block is executed
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d"%c)
# Using Exception with except statement. If we print(Exception) it will
return exception class
except Exception:
print("can't divide by zero")
print(Exception)
else:
print("Hi I am else block")
• The try...finally block
• Python provides the optional finally statement, which is used with
the try statement. It is executed no matter what exception occurs
and used to release the external resource. The finally block provides
a guarantee of the execution.
• We can use the finally block with the try block in which we can pace
the necessary code, which must be executed before the try
statement throws an exception.
• Syntax
try:
# block of code
# this may throw an exception
finally:
# block of code
# this will always be executed
• How the try and except works –
• First try clause is executed i.e. the code
between try and except clause.
• If there is no exception, then only try clause will run, except clause
will not get executed.
• If any exception occurs, the try clause will be skippeed
and except clause will run.
• If any exception occurs, but the except clause within the code
doesn’t handle it, it is passed on to the outer try statements. If the
exception is left unhandled, then the execution stops.
• A try statement can have more than one except clause.
try:
fileptr = open("file2.txt","r")
try:
fileptr.write("Hi I am good")
finally:
fileptr.close()
print("file closed")
except:
print("Error")
Program to Check for ZeroDivisionError Exception
x = int(input("Enter value for x: "))
y = int(input("Enter value for y: "))
try:
result = x / y
except ZeroDivisionError:
print("Division by zero!")
else:
print(f"Result is {result}")
finally:
print("Executing finally clause")
• File Operation
try:
fh = open ("testfile", "w")
fh.write ("This is my test file for exception handling!!")
finally:
print "Error: can\'t find file or read data“

If you do not have permission to open the file in writing mode, then
this will produce the following result −
Error: can't find file or read data
try:
fh = open("testfile", "w")
try:
fh.write("This is my test file for exception handling!!")
finally:
print "Going to close the file"
fh.close()
except IOError:
print "Error: can\'t find file or read data“

When an exception is thrown in the try block, the execution


immediately passes to the finally block. After all the statements in
the finally block are executed, the exception is raised again and is
handled in the except statements if present in the next higher layer of
the try-except statement.
• Multithreading
• In computing, a process is an instance of a computer program that
is being executed. Any process has 3 basic components:
• An executable program.
• The associated data needed by the program (variables, work space,
buffers, etc.)
• The execution context of the program (State of process)
• A thread is an entity within a process that can be scheduled for
execution. Also, it is the smallest unit of processing that can be
performed in an OS (Operating System).
• In simple words, a thread is a sequence of such instructions within
a program that can be executed independently of other code. For
simplicity, you can assume that a thread is simply a subset of a
process!
• A thread contains all this information in a Thread Control Block
(TCB):
• Thread Identifier: Unique id (TID) is assigned to every new thread
• Stack pointer: Points to thread’s stack in the process. Stack contains
the local variables under thread’s scope.
• Program counter: a register which stores the address of the
instruction currently being executed by thread.
• Thread state: can be running, ready, waiting, start or done.
• Thread’s register set: registers assigned to thread for computations.
• Parent process Pointer: A pointer to the Process control block (PCB)
of the process that the thread lives on.
• Multithreading is defined as the ability of a processor to execute
multiple threads concurrently.
• In a simple, single-core CPU, it is achieved using frequent switching
between threads. This is termed as context switching. In context
switching, the state of a thread is saved and state of another thread
is loaded whenever any interrupt (due to I/O or manually set) takes
place. Context switching takes place so frequently that all the
threads appear to be running parallelly (this is termed
as multitasking).
• Thread class that implements threading. The methods provided by
the Thread class are as follows −
• run() − The run() method is the entry point for a thread.
• start() − The start() method starts a thread by calling the run
method.
• join([time]) − The join() waits for threads to terminate.
• isAlive() − The isAlive() method checks whether a thread is still
executing.
• getName() − The getName() method returns the name of a thread.
• setName() − The setName() method sets the name of a thread.
• import thread # import the thread module
• import time # import time module
def cal_sqre(num): # define the cal_sqre function
print(" Calculate the square root of the given number")
for n in num:
time.sleep(0.3) # at each iteration it waits for 0.3 time
print(' Square is : ', n * n)
def cal_cube(num): # define the cal_cube() function
print(" Calculate the cube of the given number")
for n in num:
time.sleep(0.3) # at each iteration it waits for 0.3 time
print(" Cube is : ", n * n *n)
arr = [4, 5, 6, 7, 2] # given array
t1 = time.time() # get total time to execute the functions
cal_sqre(arr) # call cal_sqre() function
cal_cube(arr) # call cal_cube() function
print(" Total time taken by threads is :", time.time() -
t1) # print the total time
• Synchronizing Threads
• It is a thread synchronization mechanism that ensures no two threads can
simultaneously execute a particular segment inside the program to access
the shared resources. The situation may be termed as critical sections. We
use a race condition to avoid the critical section condition, in which two
threads do not access resources at the same time.

import time # import time module


import threading
from threading import *
def cal_sqre(num): # define a square calculating function
print(" Calculate the square root of the given number")
for n in num: # Use for loop
time.sleep(0.3) # at each iteration it waits for 0.3 time
print(' Square is : ', n * n)
def cal_cube(num): # define a cube calculating function
print(" Calculate the cube of the given number")
for n in num: # for loop
time.sleep(0.3) # at each iteration it waits for 0.3 time
print(' Square is : ', n * n)
def cal_cube(num): # define a cube calculating function
print(" Calculate the cube of the given number")
for n in num: # for loop
time.sleep(0.3) # at each iteration it waits for 0.3 time
print(" Cube is : ", n * n *n)
ar = [4, 5, 6, 7, 2] # given array
t = time.time() # get total time to execute the functions
#cal_cube(ar)
#cal_sqre(ar)
th1 = threading.Thread(target=cal_sqre, args=(ar, ))
th2 = threading.Thread(target=cal_cube, args=(ar, ))
th1.start()
th2.start()
th1.join()
th2.join()
print(" Total time taking by threads is :", time.time() - t) # print the total time
print(" Again executing the main thread")
print(" Thread 1 and Thread 2 have finished their execution.")
• Program to handle multiple errors with one except statement
def fun(a):
if a < 4:
# throws ZeroDivisionError for a = 3
b = a/(a-3)
# throws NameError if a >= 4
print("Value of b = ", b)
try:
fun(3)
fun(5)
# note that braces () are necessary here for multiple exceptions
except ZeroDivisionError:
print("ZeroDivisionError Occurred and Handled")
except NameError:
print("NameError Occurred and Handled")

You might also like