ELI5: what is the exception in programming?

64 views Jan 3, 2026 2 min read

Imagine you're making a peanut butter sandwich.

  • Normal procedure: Get bread, peanut butter, and a knife. Spread the peanut butter. Enjoy!
Now, let's think about things that could go wrong – these are like exceptions in programming.
  • 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!
In programming, a program follows a set of instructions, like our sandwich recipe. But sometimes, something unexpected happens that stops the program from doing what it's supposed to do. These unexpected events are called exceptions.

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.
When an exception happens, the program needs to do something different than usual. Instead of crashing, it should try to handle the problem. Like if you're out of bread, you could use crackers instead, or maybe make a different snack altogether! Programmers write special 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!

Follow-Up Questions

Still curious? Ask a follow-up!

Test Your Understanding

Take a quick quiz and challenge your friends!

Want to learn more?

Ask another question and get a simple explanation!

Ask a New Question