livepython.net
CHAPTER 17Handling Errors (Exceptions)
17.2  TRY AND EXCEPT

Python try except: Catch Errors Without Crashing

Python try and except: Catch an Error

A try and except statement lets your program catch an exception instead of crashing. You put the risky code under try:, and the code that handles the problem under except:.

PYTHONedit me
try:
    age = int(input())
    print("Next year you will be", age + 1)
except ValueError:
    print("That is not a whole number.")
print("Goodbye!")
OUTPUT
That is not a whole number.
Goodbye!

The user typed twenty, so int() failed. But instead of a red error, the program printed a friendly message and carried on to Goodbye!. Now type 20 in the Input box and run it again: the except block is skipped.

Think of it like a safety net under a trapeze artist. If the jump goes well, the net does nothing. If they fall, the net catches them, and the show goes on.

How Python runs it

  1. Python runs the lines in the try block, one by one.
  2. If no error happens, it skips the except block completely.
  3. If a line fails, Python jumps straight to except. The rest of the try block is skipped.
  4. After either path, the program carries on below.

That's why Next year you will be never printed for twenty: the line above it failed, so Python jumped away.

The rules

  • try and except each end with a colon, and their blocks are indented, like if and else.
  • except lines up with its try.
  • A try needs at least one except (or a finally, which you'll meet in the next topic).
  • Put only the risky lines in the try block. Here, that's the int() line and the line that needs its result.

Common beginner doubt: "Is this the same as checking with if?" They do a similar job. if checks before, which is great when the check is easy, like people > 0. try simply tries, and handles the failure afterwards. Checking whether some text is a valid number is hard with if, but easy with try.

try runs the risky code; if it fails, Python jumps to except, and the program carries on.

your turnPredict the output

What will this print?

try: n = int(input()) print("A") except ValueError: print("B") print("C")

The user types: abc

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

Put the lines in order to catch bad input

  1. except ValueError:
  2. try:
  3. print(n * 2)
  4. print("Not a number")
  5. n = int(input())

The user types: abc

These lines are mixed up. Put them back in order, then press Check.

Catch a Specific Error, Not Every Error

The word after except is the error type it catches. except ValueError: catches a ValueError, and nothing else. Any other error still stops the program, as usual.

PYTHONedit me
try:
    people = int(input())
    print("Each gets", 100 / people)
except ValueError:
    print("Please type a number.")
OUTPUT
ZeroDivisionError: division by zero

0 is a fine number, so there's no ValueError. The division fails with a ZeroDivisionError, which this except doesn't catch. You'll learn to catch both in the next lesson.

Think of it like a goalkeeper who only guards one goal. Shots at that goal are stopped. Shots anywhere else go straight through.

The rules

  • Write the error you expect: except ValueError: around int(), except KeyError: around a dictionary lookup.
  • Errors you didn't expect still show up, with their full message. That's a good thing: they're usually bugs.

Avoid: a bare except

You can write except: with no type at all. It catches every error, including your own typos:

PYTHONedit me
try:
    total = 100
    print(totl / 4)
except:
    print("Please type a number.")
OUTPUT
Please type a number.

There's no input here at all! The real problem is a NameError: totl is a typo. But the bare except: swallowed it and printed a message that's simply wrong. You could hunt for this bug for an hour.

Good: name the error

PYTHONedit me
try:
    total = 100
    print(totl / 4)
except ValueError:
    print("Please type a number.")
OUTPUT
NameError: name 'totl' is not defined

Now the typo shows itself, with its line, and you can fix it in seconds.

Common mistake: you may also see except Exception: in other people's code. It's almost as wide as a bare except:, so the same advice applies: name the error you expect.

Name the error you expect after except. A bare except: hides every error, even your own typos.

your turnFill the gap

Catch the right error

try: print(int("abc")) ? print("Not a number")

It should print: Not a number

Which piece makes this code work?
your turnPick the right idea

Why is a bare except: a bad idea?

Think about it, then pick one.

Several except Blocks

One try can have several except blocks, one for each error you expect. Each block gives its own message, so the user knows exactly what went wrong.

PYTHONedit me
try:
    total = int(input())
    people = int(input())
    print("Each pays", total // people)
except ValueError:
    print("Please type whole numbers.")
except ZeroDivisionError:
    print("There must be at least one person.")
OUTPUT
There must be at least one person.

Try other inputs: 500 and 4 prints the share, and 500 and four gives the ValueError message.

Think of it like a hospital with different doctors. A broken arm goes to one doctor, a toothache to another. Each problem is sent to the one who knows how to handle it.

How Python picks a block

  • When an error happens, Python checks the except blocks from top to bottom.
  • The first block whose type matches runs. The others are skipped.
  • Only one except block runs, never two.
  • If none matches, the error stops the program as usual.

One block for two errors

When two errors need the same message, put their types in a tuple (chapter 14):

PYTHONedit me
try:
    a = int(input())
    b = int(input())
    print(a // b)
except (ValueError, ZeroDivisionError):
    print("Please type two numbers, and the second one can't be 0.")
OUTPUT
Please type two numbers, and the second one can't be 0.

The round brackets matter: except (ValueError, ZeroDivisionError):. Without them, Python gives a syntax error.

Common beginner doubt: "Do I need a separate try for each line?" No. One try can hold a few risky lines, and the except blocks sort out which error happened. Keep it to the lines that belong together, like reading two numbers and dividing them.

Add one except block per error you expect. Python runs the first one that matches.

your turnType the output

Type what this prints

try: a = int(input()) b = int(input()) print(a // b) except ValueError: print("number please") except ZeroDivisionError: print("not zero")

The user types: 80

Read the code line by line, then type the output exactly.
your turnPredict the output

What will this print?

def greet(name="friend"): return "Hi " + name print(greet())
Your turn! What will this code show on the screen?

except ValueError as e: Get the Error Message

Add as e after the error type, and Python stores the exception in the variable e. Print e, and you get the error's message: the text after the colon.

PYTHONedit me
try:
    number = int(input())
except ValueError as e:
    print("Problem:", e)
OUTPUT
Problem: invalid literal for int() with base 10: 'ten'

Think of it like a parcel that arrives damaged. You can simply say "something broke", or you can open the delivery note and read exactly what happened.

The rules

  • e is just a variable name. error works too: except ValueError as error:.
  • e only exists inside its except block.
  • as e works with a tuple too: except (ValueError, ZeroDivisionError) as e:.
PYTHONedit me
try:
    print(10 / 0)
except ZeroDivisionError as e:
    print("Oops:", e)
OUTPUT
Oops: division by zero

Who is the message for?

Error messages are written for programmers. invalid literal for int() with base 10 means nothing to most users. So:

  • For the user, print your own friendly message: Please type a whole number.
  • For you, while you're building and testing the program, print(e) is a quick way to see what really went wrong.

KeyError messages are short

PYTHONedit me
ages = {"Sunny": 12}
try:
    print(ages["Lucky"])
except KeyError as e:
    print("Missing:", e)
OUTPUT
Missing: 'Lucky'

A KeyError's message is only the missing key, in quotes. Useful, but you'll usually want to write your own sentence around it.

Common beginner doubt: "Can I get the type's name too?" The type is the word after except, so you already know it: inside except ValueError as e:, it's a ValueError.

except ValueError as e: puts the error in e, and print(e) shows its message.

your turnPredict the output

What will this print?

try: print(5 // 0) except ZeroDivisionError as e: print("Error:", e)
Your turn! What will this code show on the screen?
your turnFix the code

Fix the code so it prints: Error: division by zero

It should print: Error: division by zero

try:
    print(8 / 0)
except ZeroDivisionError:
    print("Error:", e)
This code does not work yet. Fix it, then press Run.

Practice: try and except

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

  1. 152.Python Program to Double a Number with try and exceptEasySolve
  2. 153.Python Program to Split a Bill SafelyMediumSolve