livepython.net
CHAPTER 17Handling Errors (Exceptions)
17.3  ELSE AND FINALLY

Python try, except, else and finally Explained

try except else: Run Code Only When It Worked

The else block of a try runs only when the try block had no error. It's the place for the code that should run after the risky part succeeded.

PYTHONedit me
try:
    age = int(input())
except ValueError:
    print("Please type a whole number.")
else:
    print("Saved! Next year you will be", age + 1)
OUTPUT
Saved! Next year you will be 16

Type fifteen in the Input box and run it again: now only the except block runs.

Think of it like an exam. If you fail, you get the "try again" letter (except). If you pass, and only then, you get the certificate (else).

The rules

  • else comes after all the except blocks.
  • It runs only when the try block finished with no error.
  • It needs at least one except before it.
  • Exactly one of them runs: an except block, or the else block.

Why not put it all in try?

Because a big try can catch errors you didn't mean to catch.

Avoid: a big try

PYTHONedit me
try:
    qty = int(input())
    price = int("12.5")
    print("Total:", qty * price)
except ValueError:
    print("Please type a whole number.")
OUTPUT
Please type a whole number.

The user typed 3, a perfect whole number! The real bug is int("12.5") on line 3: it should be float(). But the except caught that ValueError too, and blamed the user.

Good: only the risky line in try

PYTHONedit me
try:
    qty = int(input())
except ValueError:
    print("Please type a whole number.")
else:
    price = int("12.5")
    print("Total:", qty * price)
OUTPUT
ValueError: invalid literal for int() with base 10: '12.5'

Now the bug shows itself with the right line, and you can fix it with float(). The except only covers the line that reads the input.

else runs only when the try block had no error. Keep try small, and put the next steps in else.

your turnPredict the output

What will this print?

try: n = int(input()) except ValueError: print("bad") else: print("good", n)

The user types: 7

Your turn! What will this code show on the screen?

finally: Code That Always Runs

The finally block runs every time: when the try worked, when an error was caught, and even when an error was not caught. It's for the last steps that must happen no matter what.

PYTHONedit me
try:
    n = int(input())
    print("Half:", n / 2)
except ValueError:
    print("Not a number")
finally:
    print("Thanks for using the calculator")
OUTPUT
Not a number
Thanks for using the calculator

Type 10 and run it again: Half: 5.0, and then the thank-you line still appears.

Think of it like locking the shop at the end of the day. Good day or bad day, busy or quiet, the door gets locked.

Even when the error isn't caught

PYTHONedit me
try:
    print(10 / 0)
finally:
    print("Cleaning up")
OUTPUT
Cleaning up
ZeroDivisionError: division by zero

There's no except here, so the ZeroDivisionError still stops the program. But first, Python runs the finally block. A try with only a finally is allowed.

The rules

  • finally comes last, after the except blocks and the else (if there is one).
  • It always runs, whatever happened in the try.
  • It doesn't catch anything. An uncaught error still stops the program, right after finally.

What is it for?

  • Saying goodbye or printing a summary at the end.
  • Closing things you opened. In chapter 19, you'll open files, and finally (or the shorter with) makes sure they get closed.

Common beginner doubt: "Why not just put the line after the whole try?" A line after the try statement only runs if the program is still alive. When an error isn't caught, the program stops, and that line never runs. The finally block runs even then.

finally always runs, error or no error, so put the must-do last steps there.

your turnType the output

Type what this prints

try: print(10 // int(input())) except ZeroDivisionError: print("zero") finally: print("end")

The user types: 0

Read the code line by line, then type the output exactly.
your turnPick the right idea

When does a finally block run?

Think about it, then pick one.

try, except, else and finally Together

A full try statement has up to four parts, always in the same order: try, then the except blocks, then else, then finally. You'll rarely need all four, but it helps to see them together.

PYTHONedit me
text = input()
try:
    number = int(text)
except ValueError:
    print(text, "is not a number")
else:
    print(text, "squared is", number ** 2)
finally:
    print("Checked:", text)
OUTPUT
7 squared is 49
Checked: 7

Type seven and run it again: seven is not a number, then Checked: seven.

Think of it like a trip to the bank. You try to take out money. If the card is refused, you get an explanation (except). If it works, you count your cash (else). Either way, you take your card back (finally).

Which blocks run?

What happens in tryBlocks that run
no errortry, else, finally
an error that an except catchestry up to the error, that except, finally
an error that no except catchestry up to the error, finally, then the program stops

The order rules

  • try first, always.
  • Then one or more except blocks.
  • Then else, if you want one (only with an except).
  • Then finally, if you want one, at the very end.

Write them in another order, and Python gives a syntax error.

A real example

PYTHONedit me
scores = {"Sunny": 82, "Rocky": 67}
name = input()
try:
    score = scores[name]
except KeyError:
    print("No score for", name)
else:
    print(name, "scored", score)
finally:
    print("Search finished")
OUTPUT
No score for Lucky
Search finished

Common beginner doubt: "Do I need else and finally every time?" No. Most of the time, try and except are enough. Add else when there's work that should happen only after success, and finally when something must happen at the end no matter what.

The order is try, except, else, finally. else runs on success, finally runs every time.

your turnOrder the lines

Put the full try statement in order

  1. except ValueError:
  2. finally:
  3. try:
  4. print("ok")
  5. else:
  6. n = int(input())
  7. print("done")
  8. print("bad")

The user types: 5

These lines are mixed up. Put them back in order, then press Check.
your turnPick the right idea

Which function name follows PEP 8?

Think about it, then pick one.

Practice: else and finally

Solve these to lock in what you learned in this topic. Each one runs in your browser.

  1. 154.Python Program to Check Even or Odd with try, except and elseEasySolve
  2. 155.Python Program to Make a Ticket Machine with finallyMediumSolve