|
| 1 | +# Fun with Exceptions |
| 2 | +# Exceptions handle errors that you can't know about until running the application |
| 3 | +# |
| 4 | +# They are different than errors that are known about in advance |
| 5 | + |
| 6 | +print("let's do something totally wrong. See if you can spot me in the output!") |
| 7 | +print("Too many parentheses")) |
| 8 | + |
| 9 | + |
| 10 | +print("More wrongness. Do I get printed?") |
| 11 | +print("Who has ever "messed up" quotations marks?") |
| 12 | + |
| 13 | + |
| 14 | +# Notice how both failed to execute AND didn't show the initial print. |
| 15 | +# |
| 16 | +# That's what happens with syntax errors. |
| 17 | +# |
| 18 | +# But how about logical errors that ARE syntactically correct? |
| 19 | + |
| 20 | +print("What happens now? Do you see me printed?") |
| 21 | +value = 1/0 |
| 22 | + |
| 23 | +# Got a ZeroDivisionError at runtime |
| 24 | +# |
| 25 | +# Notice intial print DID display this time |
| 26 | +# |
| 27 | +# Check out the error |
| 28 | +# |
| 29 | +# Getting a descriptive error is good |
| 30 | +# |
| 31 | +# WAY better than getting a non-descriptive or even non-existent one |
| 32 | +# |
| 33 | +# So always pay attention to anything an error is telling you |
| 34 | + |
| 35 | + |
| 36 | +# You can handle these errors in your code |
| 37 | + |
| 38 | +try: |
| 39 | + print("Divide by zero again", 1 / 0) |
| 40 | +except ZeroDivisionError: |
| 41 | + print("Don't divide by zero silly.") |
| 42 | + |
| 43 | +print("handled the exception above, carrying on") |
| 44 | + |
| 45 | + |
| 46 | +# Notice that we "caught" a specific exception. It is a best practice to only catch specific exceptions |
| 47 | +# |
| 48 | +# To put it another way it is a VERY BAD THING to catch generic exceptions Here is why that's considered an anti-pattern |
| 49 | + |
| 50 | + |
| 51 | +try: |
| 52 | + print("Divide by zero again", 1 / "spam") |
| 53 | +except: |
| 54 | + print("Don't divide by zero silly.") |
| 55 | + |
| 56 | +print("Total lie!. The problem was not dividing by zero. It was a type error") |
| 57 | + |
| 58 | + |
| 59 | +# variation on previous step |
| 60 | + |
| 61 | +try: |
| 62 | + print("Divide by zero again", 1 / "spam") |
| 63 | +except Exception: |
| 64 | + print("Don't divide by zero silly.") |
| 65 | + |
| 66 | +print("Still wrong. Handling the base Exception is a 'catch all'") |
| 67 | + |
| 68 | +# If you must handle every exception then make sure to retain the relevant error info. |
| 69 | +# |
| 70 | +# For example, you may have requirement that end user never sees a program error. |
| 71 | +# |
| 72 | +# In that case make sure to log/record the error details and then present something more palatable to end user |
| 73 | + |
| 74 | + |
| 75 | +try: |
| 76 | + spam = "nonsense" / 42 |
| 77 | +except ZeroDivisionError: |
| 78 | + print("Don't divide by zero silly.") |
| 79 | +except Exception as e: # notice we can refer to the exception using 'as' |
| 80 | + # log the exception somewhere, probably including the stack trace |
| 81 | + print("So sorry end user. Something broke!") |
| 82 | + |
| 83 | +# Python also allows you do a couple more things with exceptions |
| 84 | +# |
| 85 | +# One is an 'else' block which runs when there was NOT an exception This is not that commonly used but every now and then is helpful |
| 86 | + |
| 87 | + |
| 88 | +print("Attempting to create message") |
| 89 | +try: |
| 90 | + message = "nothing" + "wrong" + "here" |
| 91 | +except TypeError: |
| 92 | + print("Unable to create message") |
| 93 | +else: |
| 94 | + print("Message successfully created") |
| 95 | + |
| 96 | +# The last piece is the 'finally' block which is run no matter what happened |
| 97 | + |
| 98 | + |
| 99 | +print("prepare for breakage") |
| 100 | + |
| 101 | +try: |
| 102 | + value = True + " nonsense" # change to str(True) and see what happens |
| 103 | +except TypeError as e: |
| 104 | + print(f"Something broke! Details: {e}") |
| 105 | +else: |
| 106 | + print(f"smooth sailing. value is {value}") |
| 107 | +finally: |
| 108 | + print("clean up mess as needed") |
| 109 | + |
| 110 | +# you can raise exceptions intentionally as well |
| 111 | +# |
| 112 | +# If there's no better choice can use the Generic Exception |
| 113 | +# |
| 114 | +# It's a best practice to choose the most appropriate type of Error |
| 115 | + |
| 116 | + |
| 117 | +age = -10 |
| 118 | + |
| 119 | +if age < 0: |
| 120 | + raise ValueError("Invalid age - must be greater than or equal to zero") |
| 121 | + |
| 122 | + |
| 123 | +raise Exception("Something bad happened") |
| 124 | + |
| 125 | +# You can also create your own Exception types. |
| 126 | +# |
| 127 | +# This will make more sense when we cover Classes next session |
| 128 | +# |
| 129 | +# but here's a sneak peek |
| 130 | + |
| 131 | + |
| 132 | + |
| 133 | +class SocialDistanceError(Exception): |
| 134 | + def __init__(self, distance): |
| 135 | + super().__init__(f"Stay 6 feet away, not {distance}") |
| 136 | + |
| 137 | + |
| 138 | +distance_feet = 4 |
| 139 | + |
| 140 | +if distance_feet < 6: |
| 141 | + raise SocialDistanceError(distance_feet) |
0 commit comments