Q1: (Exception Handling): (30 points) Write a program called ExceptionHandling.p
ID: 3719370 • 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
As per your requirement I have written python code which fulfill all your requirements please follow it step by step clearly
def div(a,b):
return a/b
def getElement():
list_Element = [1]
return list_Element[1]
def addOfTwoElemRef(a,b):
return a+b
def getInputIntFunction():
return int(raw_input('Enter a number : '))
def main():
try:
responseContent = div(a,0)
except ZeroDivisionError:
print 'We cannot divide by zero.'
except:
print 'Unknown error.'
try:
responseContent = addOfTwoElemRef(1,'str')
except TypeError:
print 'Please provide correct types while performing addition.'
except:
print 'Unknown error.'
try:
responseContent = getInputIntFunction()
except ValueError:
print 'Cannot convert from string to int.'
except:
print 'Unknown error.'
try:
responseContent = getElement()
except IndexError:
print 'Accessing an element which is out of bound.'
except:
print 'Unknown error.'
main()
OUTPUT:
We cannot divide by zero.
Please provide correct types while performing addition.
Enter a number : as
Cannot convert from string to int.
Accessing an element which is out of bound.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.