Lesson 39 of 60
โฎPrev Nextโฏ

PY-101 ยท Files and errors

try, except and finally

โฑ 8 min ๐Ÿ Real Python 3 ๐ŸŽฌ Animated

39of 60

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    โšก The 30-second answer

    try runs code that might fail; if it raises an exception, the matching except block handles it instead of the program crashing. else runs when nothing failed, and finally always runs, error or not. Catch specific errors such as ValueError, not everything.

    • Catch specific exceptions
    • Use else and finally
    • Keep a program running after bad input

    Try it

    Watch it come alive, run it yourself, then prove it. Real Python, right on this page.

    Watch Python run the example. Every variable is a jar; watch the values change and the output appear.

    try, except and finally, running
    1. for text in ["12", "twelve", "0"]:
    2. try:
    3. n = int(text)
    4. result = 100 / n
    5. except ValueError:
    6. print(text, "-> not a number")
    7. except ZeroDivisionError:
    8. print(text, "-> cannot divide by zero")
    9. else:
    10. print(text, "->", result)
    11. finally:
    12. print("checked", text)
    Press โ–ถ to watch Python run this, one line at a time.
    1. The problemA user types "twelve" where you expected 12. Without error handling the whole app crashes. With try/except it says "please type a number" and carries on.
    2. The Python ideatry:try runs code that might fail; if it raises an exception, the matching except block handles it instead of the program crashing.
    3. In real lifePayment code wraps the call to the bank in try/except so a timeout shows "please try again" instead of an error page.

    Start with a question

    A user types "twelve" where you expected 12. Without error handling the whole app crashes. With try/except it says "please type a number" and carries on.

    Real input is messy and networks fail. Handling errors is what separates a script from a product.

    Explain it like I'm 10

    try is "have a go". except is the safety net that catches you if you slip. finally is tidying up, whether you slipped or not.

    The technical explanation

    except ValueError: catches only ValueError. You can list several: except (ValueError, TypeError):.

    except ValueError as e: gives you the error message in e.

    else runs only if the try block succeeded; finally always runs, which is ideal for cleanup.

    Syntax

    try:
        ...
    except SomeError as e:
        ...
    else:
        ...
    finally:
        ...

    โ–ถ Run the example ๐ŸŽฌ Watch it come alive

    Real-world scenario

    Payment code wraps the call to the bank in try/except so a timeout shows "please try again" instead of an error page.

    Ready for more?The full lesson adds the technical explanation, interview questions and quick revision.

    Test yourself

    5 questions. Get 4 right and this lesson is marked complete.

    1. 1. When does except run?
    2. 2. When does finally run?
    3. 3. When does else run in try/except/else?
    4. 4. int("hi") raises?
    5. 5. Why avoid a bare except:?

    Questions people ask

    What is the difference between an error and an exception in Python?

    In everyday speech they mean the same thing. Technically, an exception is the object Python raises when something goes wrong, and you can catch it with except.

    Should I use try/except or check with if first?

    Python style often prefers "try it and handle the failure" (EAFP), especially for conversions and files, because the check and the action can drift apart.

    Interview questions

    How this topic comes up in Python interviews. Answer out loud first, then open the model answer.

    beginner What is the difference between an error and an exception in Python?

    In everyday speech they mean the same thing. Technically, an exception is the object Python raises when something goes wrong, and you can catch it with except.

    beginner Should I use try/except or check with if first?

    Python style often prefers "try it and handle the failure" (EAFP), especially for conversions and files, because the check and the action can drift apart.

    intermediate When does except run?

    When the try block raises a matching error. Only on a matching exception.

    intermediate When does finally run?

    Always. Error or not.

    Quick revision

    Remember

    • Catch specific exceptions
    • Use else and finally
    • Keep a program running after bad input
    • A bare except: catches everything, including typos in your own code, and hides real bugs. Name the errors you expect.

    Syntax

    try:
        ...
    except SomeError as e:
        ...
    else:
        ...
    finally:
        ...

    Official documentation