loop
Exceptions

Module 4 · Exceptions · Lesson 1 of 6

Errors are part of the job

Here's a truth every programmer learns: things go wrong. Not because you're careless, but because code that looks perfect still meets the real world — a user types letters where you expected a number, a file isn't there, a calculation divides by zero. Accepting that is the first step to handling it gracefully.

There are really two kinds of trouble: errors in the data (good code, bad input) and errors in the code itself (the bugs you write). This section tackles both. Start with the data kind — watch a tiny, “obviously fine” program fall over.

One bad input, and it all stops
value = int(input("Enter a number: "))print("Reciprocal:", 1 / value)
Traceback (most recent call last):
  File "main.py", line 1, in <module>
    value = int(input("Enter a number: "))
ValueError: invalid literal for int() with base 10: 'ten'

When something goes wrong that Python can't handle, it raises an exception and stops, printing a traceback. Read it bottom-up: the last line is the most useful — it names the exception (here, ValueError) and gives a short reason. The lines above show where it happened.

Run it yourselfruns in your browser · Python
main.py

Your instinct might be to check the input first — make sure it's all digits before converting. You could, but Python prefers a different philosophy, summed up as “it's easier to ask forgiveness than permission.” Rather than trying to prevent every error in advance, let it happen — and be ready to catch it. That's next.