Four Parts of Exception Handling
- try: Lets you test a block of code for errors
- except: Lets you handle the error
- else: lets you execute the code when there isn't an error
- finally: always executes the code, regardless of any error
Handling the Initial Error
-
How can you handle an error when:
- A user enters bad input?
- There is an error in a calculation?
-
Handle the error gracefully with exception handling!
1 2 3 4 5 6 7 8 |
|
https://trinket.io/python/4742df2d3a
Using else When an Error Didn't Happen
We can use an else block to execute a block of code when there are no errors:
1 2 3 4 5 6 7 8 9 10 |
|
Finally, Using finally to clean up
The finally block will always execute, no matter if an error occurs or the code executes without an error
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|