Using Python Write a program called ExceptionHandlingpy that
Using Python: 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 the errors, the way we did in the ExceptionChaining program. Generate errors in different functions.
Solution
def div(a,b):
return a/b
def getElement():
list_ = [1]
return list_[1]
def addTwoElement(a,b):
return a+b
def getIntInput():
return int(raw_input(\'Enter a number : \'))
def main():
try:
res = div(a,0)
except ZeroDivisionError:
print \'Cannot divide by zero.\'
except:
print \'Unknown error.\'
try:
res = addTwoElement(1,\'str\')
except TypeError:
print \'Please provide correct types while performing addition.\'
except:
print \'Unknown error.\'
try:
res = getIntInput()
except ValueError:
print \'Cannot convert from string to int.\'
except:
print \'Unknown error.\'
try:
res = getElement()
except IndexError:
print \'Accessing an element which is out of bound.\'
except:
print \'Unknown error.\'
main()
OUTPUT:
