ELI5: what is the exception in programming?
Imagine you're making a peanut butter sandwich.
- Normal procedure: Get bread, peanut butter, and a knife. Spread the peanut butter. Enjoy!
- Uh oh! You open the cupboard and... no bread! This is an exception. You can't make the sandwich the usual way.
- Another problem: You reach for the peanut butter, but it's empty! Another exception!
For example, your program may try to:
- Open a file that doesn't exist.
- Divide a number by zero (which is impossible!).
- Try to use a network connection that's not working.
code to handle these exceptions gracefully. This code tells the program what to do if something goes wrong, so it doesn't just stop working.
try:
# Try to make the sandwich
getbread()
getpeanutbutter()
spreadpeanutbutter()
eatsandwich()
except NoBreadError:
# If there's no bread, make a cracker sandwich instead
getcrackers()
getpeanutbutter()
spreadpeanutbutter()
eatcracker_sandwich()
So, an exception is just a fancy word for something unexpected that happens while your program is running. Good programmers plan for these exceptions and write code to handle them, just like you might plan for running out of bread when making a sandwich!
How was this explanation?
Follow-Up Questions
Still curious? Ask a follow-up!
Test Your Understanding
Take a quick quiz and challenge your friends!
📧 Get this explanation by email
Receive this explanation in your inbox, plus get weekly simple explanations of trending topics!