Showing posts with label exception handling python program. Show all posts
Showing posts with label exception handling python program. Show all posts

Exception Handling - ZeroDivisionError

 # Exception handling 


N1 = eval(input("Enter number : "))

N2 = eval(input("Enter number : "))


try:

Res = N1/N2

except ZeroDivisionError as e:

print("ZeroDivisionError : ",e)

except:

print("Unknown error")

else:

print("Division = ",round(Res,4))

finally:

print("Exception handling complete.")

"""

Sample output

>python EH3.py

Enter number : 4

Enter number : 6

Division =  0.6667

Exception handling complete.


>python EH3.py

Enter number : 4

Enter number : 'e'

Unknown error

Exception handling complete.


>python EH3.py

Enter number : 4

Enter number : 0

ZeroDivisionError :  division by zero

Exception handling complete.

"""

Exception Handling - ArithmeticError

 # Exception handling 


N1 = eval(input("Enter number : "))

N2 = eval(input("Enter number : "))


try:

Res = N1/N2

except ArithmeticError as e:

print("ArithmeticError : ",e)

except:

print("Unknown error")

else:

print("Division = ",round(Res,4))

finally:

print("Exception handling complete.")

"""

Sample output

>python 11_EH2.py

Enter number : 4

Enter number : 5

Division =  0.8

Exception handling complete.


>python 11_EH2.py

Enter number : 4

Enter number : 's'

Unknown error

Exception handling complete.


>python 11_EH2.py

Enter number : 4

Enter number : 0

ArithmeticError :  division by zero

Exception handling complete.

"""

Exception handling in Python - IOError

 # Exception handling - IOError

# Program to display contents of file


fs = None

try:

file_name=(input("Enter file name : ")).strip()

fs = open(file_name,"r")

except IOError as e:

print(e)

except:

print("Unknown error")

else:

while(True):

line = fs.readline()

if not line:

break

print(line,end="")

finally:

if(fs):

fs.close()


"""

input file: f1.txt

# File f1.txt


Welcome to python programming!!!

"""


"""

Sample output

>python EH.py

Enter file name : f1.txt

# File f1.txt


Welcome to python programming!!!


>python EH.py

Enter file name : f11.txt

[Errno 2] No such file or directory: 'f11.txt'


"""