Skip to content
Python

Python try, except, else and finally: Handle Errors

Ihsan Ullah · 13 min read
Python try and except, Lesson 35 of the Python course: Catch errors with except, else and finally

Python course · Module 7: Files and errors · Lesson 35 of 63

Quick answer: Python try except lets your program handle an error instead of crashing. Put the risky code in try: and the plan B in except SomeError:. If the error happens, Python jumps to the matching except block and then carries on. else: runs only when no error happened, and finally: always runs, error or not. Catch specific types such as ValueError or FileNotFoundError, never everything.

In this lesson you will learn:

  • how to read a traceback, and the exceptions beginners meet most
  • how to use try and except with one or more exception types, and as e
  • the order of try, except, else and finally, shown step by step
  • why a bare except: and except Exception: can hide bugs
  • the EAFP and LBYL styles, with a real file example

Before you start: finish Lesson 34, Python CSV and JSON Files: Read, Write and Convert. You need functions and files from Lesson 32. All examples were run on Linux with Python 3.14.6 and gave exactly the same output on Python 3.15.2, the newest release on python.org.

What is an exception? Read the traceback

The Python tutorial says: “Errors detected during execution are called exceptions”. When nobody handles one, Python stops and prints a traceback:

def average(scores):
    return sum(scores) / len(scores)


def report(name, scores):
    print(name, "average:", average(scores))


report("Sara", [80, 90])
report("Ali", [])
Sara average: 85.0
Traceback (most recent call last):
  File "/home/learner/python-course/w33/step1_traceback.py", line 10, in <module>
    report("Ali", [])
    ~~~~~~^^^^^^^^^^^
  File "/home/learner/python-course/w33/step1_traceback.py", line 6, in report
    print(name, "average:", average(scores))
                            ~~~~~~~^^^^^^^^
  File "/home/learner/python-course/w33/step1_traceback.py", line 2, in average
    return sum(scores) / len(scores)
           ~~~~~~~~~~~~^~~~~~~~~~~~~
ZeroDivisionError: division by zero

Read it from the bottom up:

  • The last line says what happened: the exception type ZeroDivisionError and a message. The tutorial says “the type is printed as part of the message”.
  • The frame just above is where it happened: line 2, inside average(). The ^ marks point at the exact part, the /.
  • The frames above that show how we got there: line 10 called report(), which called average() on line 6. “Most recent call last” means the newest call is at the bottom. This is the call stack you met with recursion in Lesson 26.

Sara’s line was printed, then Ali’s empty list stopped the whole program. Handling errors keeps the program running.

Common Python exceptions

Each message below was copied from a real run on Python 3.14.6:

CodeExceptionMessage
int(“abc”)ValueErrorinvalid literal for int() with base 10: ‘abc’
“Age: ” + 25TypeErrorcan only concatenate str (not “int”) to str
{“pen”: 30}[“ruler”]KeyError‘ruler’
[10, 20, 30][5]IndexErrorlist index out of range
10 / 0ZeroDivisionErrordivision by zero
open(“missing.txt”, encoding=”utf-8″)FileNotFoundError[Errno 2] No such file or directory: ‘missing.txt’
print(totl)NameErrorname ‘totl’ is not defined
“abc”.push(“d”)AttributeError‘str’ object has no attribute ‘push’

The built-in exceptions page explains each one. For example, ValueError means the argument “has the right type but an inappropriate value”, while TypeError means the wrong type.

Python try except: the basic form

for text in ["42", "abc"]:
    try:
        number = int(text)
        print("Number:", number)
    except ValueError:
        print("Not a whole number:", text)

print("The program goes on")
Number: 42
Not a whole number: abc
The program goes on

The tutorial describes the steps:

  • First the try block runs. “If no exception occurs, the except clause is skipped”. That happened with "42".
  • If an exception happens, “the rest of the clause is skipped”. With "abc", int() failed, so print("Number:", ...) never ran. Python jumped to except ValueError, because the types match.
  • After the except block, the program continues normally.

Catch more than one exception type

Different errors often need different messages. Add one except block per type:

def share(total, people):
    try:
        each = int(total) / int(people)
    except ValueError:
        return "Please type whole numbers"
    except ZeroDivisionError:
        return "People cannot be 0"
    return f"Each person pays {each:.2f}"


print(share("900", "4"))
print(share("900", "four"))
print(share("900", "0"))

for people in ["four", "0"]:
    try:
        print(900 / int(people))
    except (ValueError, ZeroDivisionError):
        print("Bad number of people:", people)
Each person pays 225.00
Please type whole numbers
People cannot be 0
Bad number of people: four
Bad number of people: 0
  • Python checks the except blocks from top to bottom and uses the first one that matches.
  • A tuple of types in brackets, (ValueError, ZeroDivisionError), handles several types with one block.

Python 3.14: brackets are optional

Since Python 3.14 (PEP 758, listed in What’s New in Python 3.14) you can leave out the brackets:

for text in ["4", "abc", "0"]:
    try:
        print(10 / int(text))
    except ValueError, ZeroDivisionError:
        print("Bad input:", repr(text))
2.5
Bad input: 'abc'
Bad input: '0'

Python 3.13.18 rejects the same file:

  File "/home/learner/python-course/w33/step11_no_parentheses.py", line 4
    except ValueError, ZeroDivisionError:
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: multiple exception types must be parenthesized

The language reference adds a rule: brackets can be dropped only when “the as clause is not used”. Keep the brackets if your code must run on older Pythons.

Get the error message with as e

as e stores the exception object in a variable, so you can show or log the details:

for text in ["abc", "0"]:
    try:
        print(100 / int(text))
    except (ValueError, ZeroDivisionError) as e:
        print("Type:   ", type(e).__name__)
        print("Message:", e)
        print("args:   ", e.args)
Type:    ValueError
Message: invalid literal for int() with base 10: 'abc'
args:    ("invalid literal for int() with base 10: 'abc'",)
Type:    ZeroDivisionError
Message: division by zero
args:    ('division by zero',)

print(e) shows the message, and e.args holds the values the exception was made with. type(e).__name__ gives the type’s name.

else and finally: the full order

else runs only when the try block raised no exception. finally always runs, last. Watch the order:

def convert(text):
    print(f"--- convert({text!r})")
    try:
        print("try: start")
        number = int(text)
        print("try: end")
    except ValueError:
        print("except: not a number")
    else:
        print("else: got", number)
    finally:
        print("finally: always runs")


convert("42")
convert("abc")
convert(None)
--- convert('42')
try: start
try: end
else: got 42
finally: always runs
--- convert('abc')
try: start
except: not a number
finally: always runs
--- convert(None)
try: start
finally: always runs
Traceback (most recent call last):
  File "/home/learner/python-course/w33/step6_else_finally.py", line 17, in <module>
    convert(None)
    ~~~~~~~^^^^^^
  File "/home/learner/python-course/w33/step6_else_finally.py", line 5, in convert
    number = int(text)
TypeError: int() argument must be a string, a bytes-like object or a real number, not 'NoneType'
Python try except flowchart from Lesson 35: after try, else runs when there is no exception, except runs when the type matches, and finally always runs, even before an unhandled TypeError stops the program.
The order of try, except, else and finally, with the three real runs of convert(): “42”, “abc” and None.
  • "42": try finished, so else ran, then finally.
  • "abc": ValueError skipped the rest of try; except ran, else was skipped, then finally.
  • None: int(None) raised a TypeError, which no block handles. finally still ran, and then the error stopped the program. The tutorial says an unhandled exception “is re-raised after the finally clause has been executed”.

Why not put the else code at the end of try? The tutorial says else “avoids accidentally catching an exception that wasn’t raised by the code being protected”. Use finally for clean-up that must always happen, like a closing message. For files, with already closes them.

Why bare except and except Exception are dangerous

An except: with no type catches everything, including your own bugs:

def read_age(text):
    try:
        return int(txt)      # typo: txt instead of text
    except:
        return 0


print(read_age("25"), read_age("abc"))
0 0

The typo txt raises a NameError on every call, and the bare except: hides it, so even "25" gives 0. With except ValueError: the bug shows up at once:

Traceback (most recent call last):
  File "/home/learner/python-course/w33/err1_specific_except.py", line 8, in <module>
    print(read_age("25"), read_age("abc"))
          ~~~~~~~~^^^^^^
  File "/home/learner/python-course/w33/err1_specific_except.py", line 3, in read_age
    return int(txt)      # typo: txt instead of text
               ^^^
NameError: name 'txt' is not defined. Did you mean: 'text'?

except Exception: would hide this typo too. A bare except: is even wider:

print(issubclass(ValueError, Exception))
print(issubclass(FileNotFoundError, Exception))
print(issubclass(KeyboardInterrupt, Exception))
print(issubclass(KeyboardInterrupt, BaseException))
print(issubclass(SystemExit, Exception))
True
True
False
True
False

KeyboardInterrupt (what Ctrl+C raises) and SystemExit are not under Exception. PEP 8 warns that “A bare except: clause will catch SystemExit and KeyboardInterrupt exceptions, making it harder to interrupt a program with Control-C”. It also says to “limit the try clause to the absolute minimum amount of code necessary”. Catch the exact type you expect, around the one line that can fail.

EAFP vs LBYL

The Python glossary names two styles. LBYL, “Look before you leap”, checks first with if. EAFP, “Easier to ask for forgiveness than permission”, just tries and catches the exception:

from pathlib import Path

path = Path("settings.txt")

# LBYL: look before you leap
if path.exists():
    print(path.read_text(encoding="utf-8"))
else:
    print("LBYL: no settings file")

# EAFP: easier to ask for forgiveness than permission
try:
    print(path.read_text(encoding="utf-8"))
except FileNotFoundError:
    print("EAFP: no settings file")
LBYL: no settings file
EAFP: no settings file

Both work here. The glossary calls EAFP common in Python and warns that LBYL can lead to a race condition, where something changes between “the looking” and “the leaping”. With files, another program could delete the file right after exists() from Lesson 33 returned True. EAFP handles that case too. Use LBYL when the check is simple and cheap, like if people == 0.

Example: average scores from a file

This example reads scores from a file, skips bad lines and handles a missing file:

def load_scores(filename):
    scores = []
    try:
        with open(filename, encoding="utf-8") as f:
            for number, line in enumerate(f, start=1):
                try:
                    scores.append(int(line))
                except ValueError:
                    print(f"Line {number}: skipped {line.strip()!r}")
    except FileNotFoundError:
        print("No file called", filename)
    return scores


with open("scores.txt", "w", encoding="utf-8") as f:
    f.write("85\n90\nabc\n\n77\n")

for filename in ["scores.txt", "score.txt"]:
    scores = load_scores(filename)
    try:
        average = sum(scores) / len(scores)
    except ZeroDivisionError:
        print("No scores to average")
    else:
        print(f"{len(scores)} scores, average {average:.1f}")
Line 3: skipped 'abc'
Line 4: skipped ''
3 scores, average 84.0
No file called score.txt
No scores to average
  • The inner try protects one line, int(line), so one bad line does not stop the loop. int() accepts "85\n" because it ignores spaces and line breaks around the number.
  • The outer try handles the missing file score.txt, a typo.
  • else prints the average only when the division worked.

Try it yourself

Exercise 1: A safe int()

Write a function to_int(text) that returns the whole number, or None if text is not a whole number. Test it with "42", "4.5" and "".

Exercise 2: Safe division

Write safe_divide(a, b) that prints the result, or a message for ZeroDivisionError and for TypeError. Use else for the result and finally to print done. Test it with (9, 3), (9, 0) and (9, "3").

Exercise 3: Load settings safely

Write load_settings(filename) that loads a JSON file (see Lesson 34). If the file is missing or broken, print a message and return {"dark_mode": False}.

Solutions

Solution 1

def to_int(text):
    try:
        return int(text)
    except ValueError:
        return None


for text in ["42", "4.5", ""]:
    print(repr(text), "->", to_int(text))
'42' -> 42
'4.5' -> None
'' -> None

int() from Lesson 8 refuses "4.5" and the empty string, so both return None.

Solution 2

def safe_divide(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        print("Cannot divide by zero")
    except TypeError:
        print("Both values must be numbers")
    else:
        print("Result:", result)
    finally:
        print("done")


safe_divide(9, 3)
safe_divide(9, 0)
safe_divide(9, "3")
Result: 3.0
done
Cannot divide by zero
done
Both values must be numbers
done

done is printed three times, because finally runs in every case.

Solution 3

import json


def load_settings(filename):
    try:
        with open(filename, encoding="utf-8") as f:
            return json.load(f)
    except FileNotFoundError:
        print(filename, "not found, using defaults")
    except json.JSONDecodeError as e:
        print(filename, "is broken:", e)
    return {"dark_mode": False}


with open("good.json", "w", encoding="utf-8") as f:
    f.write('{"dark_mode": true}')
with open("broken.json", "w", encoding="utf-8") as f:
    f.write('{"dark_mode": true,}')

for name in ["good.json", "missing.json", "broken.json"]:
    print(load_settings(name))
{'dark_mode': True}
missing.json not found, using defaults
{'dark_mode': False}
broken.json is broken: Illegal trailing comma before end of object: line 1 column 19 (char 18)
{'dark_mode': False}

Each problem gets its own except block (json.JSONDecodeError is the error you met in Lesson 34), and the default is returned after either one.

Common mistakes

  • A bare except: hides typos and even catches Ctrl+C. Name the exception you expect.
  • A general type before a specific one. With except Exception: first and except ValueError: second, int("abc") printed Something went wrong; the ValueError block never runs.
  • Too much code in try. Errors from other lines get caught by mistake. Keep try small and put the rest in else.
  • Using e after the except block. The language reference says the name “is cleared at the end of the except clause”, so print(e) later fails with NameError: name 'e' is not defined. Save what you need inside the block.
  • Dropping the brackets together with as. except ValueError, ZeroDivisionError as e: gives SyntaxError: multiple exception types must be parenthesized when using 'as'.

Frequently asked questions

How do I catch multiple exceptions in Python?

Use one except block per type when each needs its own message. To handle several types the same way, put them in a tuple: except (ValueError, ZeroDivisionError):. Since Python 3.14 the brackets are optional when you do not use as.

What is the difference between else and finally in Python?

else runs only when the try block finished without an exception. finally runs every time, even when an exception was not handled, and it runs last. Use else for the next steps that need the try result and finally for clean-up.

What is except* in Python?

except* (Python 3.11 and newer) handles an ExceptionGroup, which the tutorial describes as an exception that “wraps a list of exception instances so that they can be raised together”. Each except* block takes the exceptions of its type out of the group. Beginners rarely need it; plain except covers normal programs.

Summary

  • Read a traceback from the bottom: the last line names the exception, the frames above show where it happened.
  • try holds the risky code; except SomeError: runs only when that type of error happens, and as e gives you the details.
  • else runs when there was no exception; finally always runs last, even before an unhandled error stops the program.
  • Catch specific types. A bare except: hides bugs and catches Ctrl+C, and except Exception: still hides typos.
  • EAFP (try first) is common in Python; LBYL (check first) suits simple, cheap checks.

Next lesson

Next: Lesson 36, Python raise and Custom Exceptions.

Sources

Ihsan Ullah

Written & tested by Ihsan Ullah

Data analyst with 3 years of experience and a Bachelor's degree in Computer Science. I write clear, practical guides on data, SQL, Python and AI.

More about me →

Leave a comment

Your email address will not be published. Required fields are marked *