# Exception Handling in Python # When a program encounters an error condition, instead of crashing # it can "throw and exception". Exceptions are better than having the # program crash, or (worst case) continue to run erroneously. A = [2,3,5] try: x = int(input("enter integer:")) #could raise error if string is not a number print(1/(x-2)) # could raise division by zero error if (x<0): raise Exception("don't be negative") # user-raised error print(A[9]) # raises index out of range error except ZeroDivisionError: print("Error: you can't divide by zero!") except IndexError: print("Error: your array isn't that big") except ValueError: x = int(input("enter a number, not something else please:")) except Exception as exp: print("Exception raised:",exp) # prints exception's message except: print("Unexpected error") # Run this program. At least it will throw the IndexError because of A[9]. # Enter 2 for x to get the divison by zero error, enter "abc" to get the # 'ValueError' and enter -1 to get the user generated exception. # Note that the last except clause catches all other errors. ## Exceptions should only be used to address situations that cannot be # predicted by the algorithm. In general, you should not raise an # exception if it is something that can be handled using conventional # methods, such as an if-else. # The following functions illustrates the correct use of exceptions: # The following function computes n! (5! = 5*4*3*2*1): def factorial(n): if (n<0): raise Exception("factorial is undefined for negative numbers") ax = 1 while n>1: ax = ax*n n -= 1 return ax #factorial def smallest(A): # smallest value in A if (len(A)==0): raise Exception("function undefined for empty arrays") ax = A[0] i = 1 while i