Q1: (Exception Handling): (30 points) Write a program called ExceptionHandling.p
ID: 3719368 • Letter: Q
Question
Q1: (Exception Handling): (30 points) Write a program called ExceptionHandling.py that demonstrates exception handling. In this program write code using your own data that generates the following errors ZeroDivisionError, ValueError, TypeError, and IndexError. Catch all the errors in the main function. If the error doesn't fall into any of these types include general Exception to handle other error types. Your data/code should generate the errors. Do not simulate or raise the errors, the way we did in the ExceptionChaining program. Generate each error in a different functionExplanation / Answer
# can generate ZeroDivisionError
def divide(x , y):
return x / y
# get the i th value in arr
# can generate IndexError
def getVal(arr , i):
return arr[i]
# read number from user and return it
# can generate ValueError
def readVal():
# get user input and convert it into int
n = int(input("Please enter an integer: "))
return n
def fxn():
x = 'abc'
return int(x)
def main():
try:
try:
print('2 / 0 :', divide(2 , 0))
except ZeroDivisionError:
print('ZeroDivisionError')
try:
arr = [ 1 , 2 , 3 ]
print('arr[5] :', getVal(arr , 5))
except IndexError:
print('IndexError')
try:
readVal()
except ValueError:
print('ValueError')
try:
fxn()
except ValueError:
print('TypeError')
except:
print('Error')
main()
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.