Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

Exception in Python

• An exception is an event, which occurs during the execution of a program that


disrupts the normal flow of the program's instructions.
• In general, when a Python script encounters a situation that it cannot cope
with, it raises an exception.
• An exception is a Python object that represents an error.
• When a Python script raises an exception, it must either handle the exception
immediately otherwise it terminates and quits.
➢ Handling an exception
• If you have some suspicious code that may raise an exception, you can defend
your program by placing the suspicious code in a try: block.
• After the try: block, include an except: statement, followed by a block of code
which handles the problem as elegantly as possible.
➢ Syntax try:
You do your operations here;
except Exception1:
If there is Exception1, then execute this block.
except Exception2:
If there is Exception2, then execute this block.
else:
If there is no exception then execute this block.
0 4th year: network programming
Exception in Python
➢ Some of the common Exception Errors are :

• IOError: if the file can’t be opened


• KeyboardInterrupt: when an unrequired key is pressed by the user such as
(ctrl – c) which is a user interrupt exception

➢ The except Clause with No Exceptions


try:
You do your operations here;
except:
If there is any exception, then execute this block.
else:
If there is no exception then execute this block.
➢ This kind of a try-except statement catches all the exceptions that occur.
Using this kind of try-except statement is not considered a good
programming practice though, because it catches all exceptions but does
not make the programmer identify the root cause of the problem that may
occur.

Dr. Elhossiny Ibrahim 1 4th year: network programming


Exception in Python
Example
➢ This example opens a file, writes content in the, file and comes out
gracefully because there is no problem at all
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError: #Raised when an input/ output operation fails,
print("Error: can\'t find file or read data") #as the print statement or the open() function
else: #when trying to open a file that does not exist.
print("Written content in the file successfully")
fh.close() Written content in the file successfully
➢ Another example tries to open a file where you do not have write
permission, so it raises an exception
try:
fh = open("testfile", "r")
fh.write("This is my test file for exception handling!!")
except IOError:
print("Error: can't find file or read data")
else:
print ("Written content in the file successfully")
Error: can't find file or read data
Dr. Elhossiny Ibrahim 2 4th year: network programming
Socket Programming
chat program (server-side)
from socket import *
try:
s=socket(AF_INET, SOCK_STREAM)
host="127.0.0.1"
port=7002
s.bind((host,port))
s.listen(5)
client, addr=s.accept()
print("connection from", addr[0])
while True:
x=client.recv(2048)
print("client : ",x.decode('utf-8'))
y=input(" server : ")
client.send(y.encode('utf-8'))
s.close()
except error as e:
print(e)
except KeyboardInterrupt :
print("chat is terminated")

Dr. Elhossiny Ibrahim 3 4th year: network programming


Socket Programming
chat program (client-side)
from socket import *
try:
s=socket(AF_INET, SOCK_STREAM)
host="127.0.0.1"
port=7002
s.connect((host,port))
while True:
y=input("client : ")
s.send(y.encode('utf-8'))
x=s.recv(2048)
print("server : ",x.decode('utf-8'))
s.close()
except error as e:
print(e)
except KeyboardInterrupt :
print("chat is terminated")

Dr. Elhossiny Ibrahim 4 4th year: network programming


time module
Time access and conversions
The epoch is the point where the time starts, and is platform dependent. For Unix, the
epoch is January 1, 1970, 00:00:00 (UTC).
The time module have many functions inside it such as:
➢ time.gmtime(0)
find out what the epoch is on a given platform.
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0,
tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)
➢ time.time()
Return the time in seconds since the epoch as a floating point number (i.e. the total
number of elapsed seconds since the epoch. 1648035743.6439402
➢ time.localtime()
Convert a time expressed in seconds since the epoch to a struct_time.
time.struct_time(tm_year=2022, tm_mon=3, tm_mday=23, tm_hour=13, tm_min=44,
tm_sec=51, tm_wday=2, tm_yday=82, tm_isdst=0)
➢ time.asctime() like time.ctime() like time.ctime(time.time())
Convert a time expressed in seconds since the epoch to a string of a form.
'Wed Mar 23 13:47:21 2022'
➢ time.sleep()
Suspend execution of the calling thread for the given number of seconds.
Dr. Elhossiny Ibrahim 5 4th year: network programming
Thread
• Getting multiple tasks running simultaneously requires a non-standard
implementation of Python (require thread).
➢ What is a thread?
• A thread is an individual and separate unit of execution that is part of a process.
• A process is a running program (run a browser, run a video game)
• Multiple thread can work together inside a process to accomplish a common goal.
• Example: Video game requires multi-task:
▪ One thread for graphics.
▪ One thread for user interface.
▪ One thread for networking in case of using multiplayer game.
• These tasks must handle in parallel and always remain responsive.
• In the figure we can see the whole blue box is a process and three threads exists
inside this process.
• Inside each thread, there are a code and local variable.
• A threads are light weight process and they do not require much memory overhead.
• A thread is a sequence of a control flow.
• The difference between the thread and the process that the thread exist entirely
inside the process and share its resources.
Dr. Elhossiny Ibrahim 6 4th year: network programming
Thread

Dr. Elhossiny Ibrahim 7 4th year: network programming


Thread
• Inside the gray box there is a global variables while each thread can share these global
variables. In the same time, each thread has its local variables and its code to control the
flow between the local and global variables.
• A single process may have multiple threads that is useful in application performs many
concurrent tasks on a shared data.
• Example: a browser has to handle landing pages (a single page that focuses visitors on
a single goal), animations, or opening multiple websites on different taps and running
video on one tap and handling another task in another tab. In all this the browser
remains responsive.
• There are two types of thread:
• Kernal thread (is the part of operating system).
• User thread (is not implemented in kernal and can be seen as an extension of
function concepts in programing languages).
• Advantages of threading:
• Multithreaded programs can run faster on computer systems with multiple CPUs.
• A program can remain responsive to input. This is true both on single and on
multiple CPUs.
• Allow to do something else while one thread is waiting for an i/o task to compute.
• Some programs are easy to express using concurrency.
• Threads of process can share the memory of global variables.
Dr. Elhossiny Ibrahim 8 4th year: network programming
Python – thread module
➢ To implement a thread in python, there are two types:
• Thread module
• Threading module
➢ Thread Module
▪ First of all, we must call the thread module.
import _thread or from _thread import *
▪ To spawn a thread, you need to call function (start_new_thread) that
available in _thread module
_thread.start_new_thread ( function, args[, kwargs] ) or
start_new_thread ( function, args[, kwargs] )
▪ This calling method enables a fast and efficient way to create new threads.
▪ This function returns immediately and the child thread starts. It takes
three arguments:
▪ 1-The function which we want to execute inside the thread. When function
returns, the thread terminates.
▪ 2-args is a tuple of arguments which we provide to our function; use an
empty tuple to call function without passing any arguments.
▪ 3- kwargs is an optional dictionary of keyword arguments.

Dr. Elhossiny Ibrahim 9 4th year: network programming


Python – thread module
Example
import _thread # calling the thread module
import time # for printing and giving delay in our functions
# Define a function for the thread with the name (print_time) and define two arguments
(the name of the thread and delay)
def print_time(threadName,delay):
count = 0 # create a counter and initialize it with 0
while count < 3: # make a loop and inside it provide a delay (sec) to be
time.sleep(delay) # able to show the thread execution because the
count += 1 # execution is fast and it difficult to see it without delay
print(threadName,"-----------",time.ctime()) #check the thread running
# Create two threads and execute the function inside them as follow:
# start_new_thread is a function inside a thread module
try:
_thread.start_new_thread(print_time,("Thread 1",1)) # the first thread
_thread.start_new_thread(print_time,("Thread 2",2)) # the second thread
except:
print("this is an error") Thread 1 ----------- Thu Mar 24 00:32:35 2022
while 1: Thread 2 ----------- Thu Mar 24 00:32:36 2022
Thread 1 ----------- Thu Mar 24 00:32:36 2022
pass
Thread 1 ----------- Thu Mar 24 00:32:37 2022
# or input() instead of while loop. Because thread
Thread 2 ----------- Thu Mar 24 00:32:38 2022
takes some times to be created, so we need to
Thread 2 ----------- Thu Mar 24 00:32:40 2022
provide mechanism to wait for the thread creation.
Dr. Elhossiny Ibrahim 10 4th year: network programming

You might also like