Exceptions
- What should intdo when the input isn’t an int?- Notice that there really isn’t a “Free” integer that could serve as a warning.
- Could return a tuple, but that would be annoying to use in most cases (i.e., having to look for a problem every time intis called.)
 
- 
    Solution: Use try/exceptblocks.~~~~ user_input = ‘’ while user_input != ‘q’: try: weight = int(input(“Enter weight (in pounds): “)) height = int(input(“Enter height (in inches): “)) bmi = (float(weight) / float(height * height)) * 703 print(f'BMI: {bmi}') print('(CDC: 18.6-24.9 normal)\n') # Source www.cdc.gov except: print('Could not calculate health info.\n')user_input = input(“Enter any key (‘q’ to quit): “) ~~~~ ~~~~ try: f = open(‘notafile.txt’) except: print(“problem opening file”) ~~~~ 
- Notice that the above approach doesn’t look at what the type of problem is. Sometimes we want to be more specific.
- In general, an Exception is an object that describes a problem: https://docs.python.org/3/library/exceptions.html
    - IndexError: Index out of bounds
- KeyError: Dictionary key not found
- ZeroDivisionError: Divide by zero.
- ValueError: Try to convert a non-int to an int.
- FileNotFoundError:
 
- 
    You can look for a specific type of error and handle accordingly: try: # Code here except ValueError: # handle the value error except FileNotFoundError: # handle filenot ofund except (KeyError, ZeroDivisionError): # Not realistic. Just an example of how to watch for two errors.
- 
    Add exception handling to the “grades” code from in-class 12 
- Benefits of this approach:
    - Don’t need to do anything if default behavior (i.e., crashing) is OK.
- One check can cover multiple lines (e.g., multiple calls to int)
- Calls will propagate up through the call stack. So, without any extra “work”, you can let an error move up to a point where it can be handled.
 def read_file(filename): # This is the wrong place to handle a # FileNotFound error f = open(filename) lines = f.readlines() ... def process_file(): try: filename = input("Enter filename") data = read_file(filename) except FileNotFoundError: print(f"File {filename} not found. Please try again") process_file();
- 
    Exceptions are objects, so they contain data (often a description of the problem.) try: int("This is not an int") except ValueError as v: print(v)
- finally
- Custom exceptions