#!/usr/bin/env python # coding: utf-8 # # Exceptions # - dealing with bugs is normal part of programming # - debugging is a very handy programming skill # # ## category of bugs # - syntax errors # - logical/semantic errros # - runtime errors/exceptions # ## exceptions # - when runtime error occurs, it creats an exception object # - program halts; Python prints out the traceback with error message # - https://docs.python.org/3/tutorial/errors.html # In[1]: print(55/0) # In[2]: alist = [] print(alist[0]) # In[3]: atup = ('a', 'b', 'c') atup[0] = 'A' # - each exception has two parts- Name: description # ## catching exceptions # - use try and except blocks # - try statement has several separate clauses/parts #
#     try:
#         # statement(s) thay may potentially throw(s) exception
#     except ExceptionName1:
#         # catch specific exception ExceptionName1
#         # statement(s) to handle the exception
#     [except ExceptionName2 as err:
#         # statements
#     ]
#     [except:
#         # catch any error not caught by previous except blocks
#     ]
#     [else:
#         # follows all except clause
#         # executes if try clause does NOT raise an exception
#     ]
#     [finally:
#         # clean-up actions that must be executed under all circumstances; 
#         # exectued on the way out when try block is left via a break, continue, or return statement
#     ]
# 
# - [ ] optional # ### example 1 # In[6]: try: x = int(input("Enter dividend: ")) y = int(input("Enter divisor: ")) quotient = x/y remainder = x%y except ZeroDivisionError as ex: print('Exception occured:', ex) print('arguments:', ex.args) except: print('Some exception occured...') else: print("quotient=", quotient) print("remainder=", remainder) finally: print("executing finally clause") # In[ ]: # ### example 2 # - input validation # In[7]: while True: try: x = int(input("Please enter a number: ")) break except ValueError: print("Oops! That was not a valid number. Try again...") # ## raising exceptions # - raise statement allows programer to throw their own exceptions # ### example 1 # In[8]: raise NameError("MyException") # In[9]: try: raise NameError('My Exception') except NameError: print('An exception flew by...') raise # ## user-defined exceptions # - one can define their own exceptions and raise them as needed # - should typically derive from the Exception class, either directly or indirectly # # ### example 1 # In[12]: class InputError(Exception): """ Exception raised for errors in the input. Attributes: expression -- input expression in which the error occured message -- explaination of the error """ def __init__(self, expression, message): self.expression = expression self.message = message # In[13]: help(InputError) # In[14]: def getInteger(): x = input('Enter an integer number: ') if not x.isdigit(): raise InputError(x, 'That is not an integer!') return int(x) # In[15]: x = getInteger() print(x) # In[ ]: