Skip to main content

What is error handling?

Errors happen. Files might not exist, APIs might be down, users might enter invalid data. Error handling lets your program deal with these problems gracefully instead of crashing.

Where do errors come from?

Errors you make as a programmer:
  • Typos and syntax mistakes (VS Code shows yellow squiggly lines)
  • Logic errors like dividing by zero (only show up when code runs)
  • Using variables before defining them
  • Calling methods that don’t exist
Errors beyond your control:
  • User enters “abc” when you need a number
  • File gets deleted after your program starts
  • Internet connection drops during API call
  • External service returns unexpected data
You might think “why not just write correct code?” But even perfect code needs error handling because the world is unpredictable. Users do unexpected things, networks fail, and files disappear.

Types of errors

Syntax errors happen when Python can’t understand your code:
Runtime errors happen when your code runs:

Why handle errors?

Here’s a program that crashes:
Here’s a program that handles the error:

Try and except

Basic error handling syntax

Common errors

Errors you’ll encounter often