[Python Programming Basics to Advanced]: Exception Handling (try/except/else/finally) | Lab 26

preview_player
Показать описание
This Python programming playlist is designed to take beginners with zero programming experience to an expert level. The course covers installation, basic syntax, practical scenarios, and efficient logic building. The course material includes PDF handouts, review questions, and covers a wide range of topics, from data types to advanced functions like Lambda and Recursive functions, Generators, and JSON data parsing.

In this lesson we will study about Exception Handling. Exceptions are the errors which will terminate the program execution and as developer we must consider every possible way to handle these errors.
In python we have try and except statements to handle any exception in the program. With try and except, there can be else and finally clauses. We will see the use of these four clauses with different examples.
Then there is also a way to generate an exception, known as raise the exception. We usually need this in Object Oriented Programming. We will use that there but will just see how we can raise an exception.
Moreover, we will see Python and Non-Python way of handling the exception. One is known as Look Before You Leap and second is It's Easy to Ask Forgiveness than Permission.

Complete Playlist:

If you have the basic programming knowledge and interested to learn Object-Oriented Programming in Python, check out this playlist:

Lab Manual 26 can be downloaded from here:

Review Question:
1- Suppose I have a Dictionary with 8 key-value pairs as shown here:
d={
'element1':5,
'element2':2,
'element3':0,
'element4':'Computer',
'element5':3.2,
'element6':False,
'element7':0,
'element8':9
}

Suppose that I want to print the reciprocal of each value inside the dictionary. So this is what I did:

print(f'Reciprocal of {v} is {1/v}')

It is going to generate errors since we can divide 0 or string or Boolean data types. Write the code in a way that if reciprocal is possible, it will print that as:
Reciprocal of 5 is 0.2.

And if reciprocal is not possible, it will print that it's not possible along with the description of the exception. For example in case of 0, this should be displayed:

Reciprocal of 0 is not possible. Exception : (division by zero)

2- I am applying a file read operation using the try/except/else/finally clause:
try:
except FileNotFoundError:
print('File does not exist!')
else:
finally:
if 'f' in locals():

This works fine but suppose in the else clause, instead of reading the file, I have written a statement to write content as:

This is going to generate error since file is opened in the read mode. We can open the file in read+write mode, but for some reasons I want the file be opened in read mode always and writing should not be allowed. Mange the code with nested try/clause such that if write operation is attempted, an appropriate message is printed instead of an exception.

#PythonProgramming #python #pythontutorial
Рекомендации по теме
Комментарии
Автор

#Review_Question-01
d={
'element1':5,
'element2':2,
'element3':0,
'element4':'Computer',
'element5':3.2,
'element6':False,
'element7':0,
'element8':9
}
for k, v in d.items():
try:
print(f'Reciprocal of {v} is {1/v}')
except ZeroDivisionError as z:
print(f'Reciprocal of 0 is not possible.Exception:({z})')
except TypeError as t:
print(f'Reciprocal of string is not possible.Exception:({t})')
except Exception as e:
print(f'Reciprocal is not present.Exception:({e})')

#Review_Question-02
try:
f=open('sample.txt', 'r')
except FileNotFoundError:
print('File does not exist!')
else:
# print(f.readlines())
try:
f.write('hello')
except:
print('File opened is not in the write mode.')
finally:
if 'f' in locals():
f.close()

nukhbaiqbal
Автор

Question No. 1: -

d={'element1':5,
'element2':2,
'element3':0,
'element4':'Computer',
'element5':3.2,
'element6':False,
'element7':0,
'element8':9}

for k, v in d.items():
try:
print(f'Reciprocal of {v} is {1/v}')
except ZeroDivisionError as z:
print("This reciprocal is not possible because ", z)
except TypeError as t:
print("This reciprocal is not possible because ", t)


Question No. 2: -

try:
f=open('sample.txt', 'r')
except FileNotFoundError:
print('File does not exist!')
else:
try:
f.write('hello')
except:
print("Writing in this code is not allowed.")
finally:
if 'f' in locals():
f.close()

MuhammadAhmad-dshu
Автор

try:
    f=open('sample.txt', 'r')
except FileNotFoundError:

else:
    try:
        f.write('hello')
    except:

        print(f.readlines())
finally:
    if 'f' in locals():
        f.close()

haseebahmad
Автор

##Review Question 1##
d={
'element1':5,
'element2':2,
'element3':0,
'element4':'Computer',
'element5':3.2,
'element6':False,
'element7':0,
'element8':9
}
for k, v in d.items():
try:
print(f'Reciprocal of {v} is {1/v}')
except Exception as z:
print(f"It is not possible | Error Description: {z} ")

##Review Question 2##
try:
f=open('sample.txt', 'r')
except FileNotFoundError:
print('File does not exist!')
else:
try:
f.write('hello')
except:
print("File is open in read mode, You can't WRITE!")
print(f.readlines())
finally:
if 'f' in locals():
f.close()

shaheerahmadkhan
Автор

Question No. 1
for k, v in d.items():
try:
print(f'Reciprocal of {v} is {1/v}')
except Exception as e:
print(f'reciprocal of {v} is not possible because of {e}')
#Review Question 2
try:
f=open('sample.txt', 'r')
except FileNotFoundError:
print('File does not exist!')
else:
#print(f.readlines())
try:
f.write('hello')
except:
print("File is opened in read mode.")
finally:
if 'f' in locals():
f.close()

abdulrehmansajid
Автор

Review # 1
d={
'element1':5,
'element2':2,
'element3':0,
'element4':'Computer',
'element5':3.2,
'element6':False,
'element7':0,
'element8':9
}


for k, v in d.items():
try:
print(f'Reciprocal of {v} is {1/v}')
except Exception as e:
print(f"It is not possible to do division by zero : Description {e}")

Review # 2
try:
f=open('sample.txt', 'r')
except FileNotFoundError:
print('File does not exist!')
else:
try:
f.write('hello')
except:
print("File is open in read-only mode!")
print(f.readlines())
finally:
if 'f' in locals():
f.close()

talhakamboh
Автор

##Review Question01
d={
'element1':5,
'element2':2,
'element3':0,
'element4':'Computer',
'element5':3.2,
'element6':False,
'element7':0,
'element8':9
}

for k, v in d.items():
try:
print(f'Reciprocal of {v} is {1/v}')
except (ZeroDivisionError, TypeError) as z:
print("Zero have no Reciprocal")

dawood
Автор

#Review question 1
for k, v in d.items():
try:
print(f'Reciprocal of {v} is {1/v}')
except Exception as e:
print(f'reciprocal of {v} is not possible because of {e}')
#Review Question 2
try:
f=open('sample.txt', 'r')
except FileNotFoundError:
print('File does not exist!')
else:
#print(f.readlines())
try:
f.write('hello')
except:
print("File is opened in read mode.")
finally:
if 'f' in locals():
f.close()

zainulhassan
Автор

Q1:
d={
'element1':5,
'element2':2,
'element3':0,
'element4':'Computer',
'element5':3.2,
'element6':False,
'element7':0,
'element8':9
}
for k, v in d.items():
try:
print(f'Reciprocal of {v} is {1/v}')
except ZeroDivisionError as z:
print(f'reciprocal of {v} is not possible. Exception:({z})')
except Exception as e:
print(f'The reciprocal of {v} is not possible. Exception:({e})')
Q2:
try:
f=open('sample.txt', 'r')
except FileNotFoundError:
print('File does not exist!')
else:
try:
f.write('hello')
except:
print("File is present in read mode")
finally:
if 'f' in locals():
f.close()

shahwarsadaqat
Автор

REVIEW QN. 1:
d={
'element1':5,
'element2':2,
'element3':0,
'element4':'Computer',
'element5':3.2,
'element6':False,
'element7':0,
'element8':9
}
for k, v in d.items():
try:
print(f'Reciprocal of {v} is {1/v}')
except ZeroDivisionError as z:
print(f'Reciprocal of 0 is not Possible! Exception:({z})')
except Exception as e:
print(f'Error occured while generation Reciprocal! Exception:({e})')

REVIEW QN. 2:
try:
f=open('sample.txt', 'r')
except FileNotFoundError:
print('File does not exist!')
else:
try:
f.write('hello')
except:
print("File is in read mode! Cannot be edited.")
finally:
if 'f' in locals():
f.close()

amaanmajid
Автор

My very respected sir. One thing has too much complicated for me.
Sir according to this example program:

hafizasadullah
Автор

##Review Question No. 1
for k, v in d.items():
try:
print(f'Reciprocal of {v} is {1/v}')
except Exception as e:
print(f'reciprocal of {v} is not possible because of {e}')
#Review Question 2
try:
f=open('sample.txt', 'r')
except FileNotFoundError:
print('File does not exist!')
else:
#print(f.readlines())
try:
f.write('hello')
except:
print("File is opened in read mode.")
finally:
if 'f' in locals():
f.close()

aliraza-zlft
Автор

#Question Number 1
d={
'element1':5,
'element2':2,
'element3':0,
'element4':'Computer',
'element5':3.2,
'element6':False,
'element7':0,
'element8':9
}
for k, v in d.items():
try:
print(f'Reciprocal of {v} is {1/v}')
except Exception as i:
print(f'Reciprocal of {v} is not possible because of {i}')

#Question number 2
try:
f=open('sample.txt', 'r')
except FileNotFoundError:
print('File does not exist!')
else:
try:
f.write('helo')
except:
print('Only read mode')
finally:
if 'f' in locals():
f.close()

irfanshehzada
Автор

from math import sqrt
b=-3
try:
print(sqrt(b))
except:
print('square root of negative number is not possible')
else:
print(3+b)

Sir according to rule if our try statement does not execute, there is no need of else statement because exception block does not allows the program to go to else block
If i am not wrong, you mentioned the same thing in videos also. But in review question no 2
Let me show my program:
try:
f=open('sample.txt', 'r')
except FileNotFoundError:
print('File does not exist!')


try:
print(f.write('hello'))
except:
print('The admin does not allow anyone to write the file')

finally:
if 'f' in locals():
f.close()

I done it this program without else statement. kindly show me my mistake in this program

hafizasadullah
Автор

q#1:
d={
'element1':5,
'element2':2,
'element3':0,
'element4':'Computer',
'element5':3.2,
'element6':False,
'element7':0,
'element8':9
}

for k, v in d.items():
try:
print(f'Reciprocal of {v} is {1/v}')
except Exception as a:
print(f"It is not possible Exception as {a}")
q#2:
try:
f=open('sample.txt', 'r')
except FileNotFoundError:
print('File does not exist!')
else:
try:
f.write('hello')
except:

print('file open in read mode you cannot write')
print(f.readlines())
finally:
if 'f' in locals():
f.close()

hamidiftikhar
Автор

Q1:

d={
'element1':5,
'element2':2,
'element3':0,
'element4':'Computer',
'element5':3.2,
'element6':False,
'element7':0,
'element8':9
}
for k, v in d.items():
try:
print(f'the reciprocal of {v} is {1/v}')
except Exception as e:
print(f'Reciprocal of {v} is not possible. Exception {(e)}')
Q2:

try:
f=open('sample.txt', 'r')
except FileNotFoundError:
print('File does not exist!')
else:
try:
f.write('hello')
except:
print(' You cannot write i file bcz it is open in read mode. thanks! ')
finally:
if 'f' in locals():
f.close()

fourcloversan
Автор

Task 1)
d={
'element1':5,
'element2':2,
'element3':0,
'element4':'Computer',
'element5':3.2,
'element6':False,
'element7':0,
'element8':9
}

for k, v in d.items():
try:
print(f'Inverse of {v} is {1/v}.')
except ZeroDivisionError as Z:
print(f'Inverse of 0 is not possible because of {Z}.')
except Exception as E:
print(f'Error occured while generating reciprocal due to {E}.')

Task 2)
try:
f=open('sample.txt', 'r')
except FileNotFoundError:
print('File does not exist.')
else:
# print(f.readlines())
try:
f.write('hello')
except:
print('Only read mode is allowed.')
finally:
if 'f' in locals():
f.close()

hishamawan
Автор

# Review Question 01:

d={
'element1':5,
'element2':2,
'element3':0,
'element4':'Computer',
'element5':3.2,
'element6':False,
'element7':0,
'element8':9
}

for k, v in d.items():
try:
print(f'Reciprocal of {v} is {1/v}')
except Exception as z:
print(f'It is not possible Exception as{z}')


# Review Question 02:

try:
f=open('sample.txt', 'r')
except FileNotFoundError:
print('File does not exist!')
else:
try:
f.write('hello')
except:

print('file open in read mode you cannot write')
print(f.readlines())
finally:
if 'f' in locals():
f.close()

muhammad-ahmad
Автор

##Review_queation1
d={
'element1':5,
'element2':2,
'element3':0,
'element4':'Computer',
'element5':3.2,
'element6':False,
'element7':0,
'element8':9
}
for k, v in d.items():
try:
print(f'Reciprocal of {v} is {1/v}')
except Exception as z:
print(f"It is not possible due to error : {z} ")
#part2
try:
f=open('sample.txt', 'r')
except FileNotFoundError:
print('File does not exist!')
else:
try:
f.write('hello')
except Exception as e:
print(e)
finally:
print(f.readlines())
finally:
if 'f' in locals():
f.close()

mukarmarashid
Автор

ANS 1:-
for k, v in d.items():
try:
print(f'Reciprocal of {v} is {1/v}')
except Exception as e:
print(f'Reciprocal of {v} is not possible.\nException:{e}')
ANS 2:-
try:
f=open('sample.txt', 'r')
except FileNotFoundError:
print('File does not exist!')
else:
# print(f.readlines())
try:
f.write('hello')
except:
print('Writing NOT allowed in the reading mode.')
finally:
if 'f' in locals():
f.close()

abdurrehmansarwar
join shbcf.ru