Home/Learn/Python A–Z/Exceptions — try/except/else/finally

Exceptions — try/except/else/finally

Beginner
Errors & Files

Python handles failures with exceptions: catch specific types with except, run success-only code in else, guarantee cleanup in finally — and never write a bare except.

Overview

Errors in Python are objects raised up the call stack until something catches them. The full statement has four parts: try (risky code), except (handlers, most-specific first), else (runs only if NO exception — keeps the try block minimal), finally (always runs — cleanup). The professional rules: catch the NARROWEST exception you can handle, never silence errors with a bare except:, and let exceptions you cannot handle propagate — a crash with a clear traceback beats silent corruption.

The Full Statement

Multiple except blocks match top-down. except (A, B) catches either. as e binds the exception object. else separates "risky" from "on success" logic.

try / except / else / finally — each part's job
def read_marks(path):
    try:
        f = open(path)                      # may raise FileNotFoundError
        marks = [int(line) for line in f]   # may raise ValueError
    except FileNotFoundError:
        print("file missing — using empty list")
        return []
    except ValueError as e:
        print(f"bad number in file: {e}")
        return []
    else:
        print(f"loaded {len(marks)} marks")  # ONLY if no exception
        return marks
    finally:
        try: f.close()                       # ALWAYS runs
        except NameError: pass               # open itself failed

# Hierarchy matters — order except blocks specific -> general:
# except ZeroDivisionError: ...     (child of ArithmeticError)
# except ArithmeticError: ...       (child of Exception)
# A bare 'except:' also catches KeyboardInterrupt/SystemExit — never use it.

EAFP — Ask Forgiveness, Not Permission

Pythonic code tries the operation and handles failure, instead of pre-checking everything (LBYL). It is cleaner AND avoids race conditions between the check and the action.

EAFP vs LBYL + the everyday exception types
scores = {"asha": 91}

# LBYL — check first (racy, verbose)
if "ravi" in scores:
    val = scores["ravi"]
else:
    val = 0

# EAFP — pythonic
try:
    val = scores["ravi"]
except KeyError:
    val = 0

# Common exceptions you'll meet daily:
int("abc")            # ValueError  — right type, bad value
# "a" + 1             # TypeError   — wrong type
# [1,2][5]            # IndexError
# {}["k"]             # KeyError
# obj.nope            # AttributeError
# 1/0                 # ZeroDivisionError

# Only catch what you can HANDLE — otherwise let it propagate.

Key Points to Remember

  • 1Catch specific exceptions; bare except: also swallows Ctrl+C — never use it
  • 2else runs only when the try block succeeded; finally always runs
  • 3EAFP (try/except) is idiomatic over pre-checking (LBYL)
  • 4ValueError = bad value, TypeError = wrong type — interviewers check you know the difference

Interview Questions

Sign in to ask Aria
1

When does the else block of a try statement run? Why use it instead of putting code in try?

MediumInfosys
2

Why is a bare except: dangerous? What does it catch that you almost never want?

MediumAmazon
3

ValueError vs TypeError — give an example each.

EasyTCS

Ask Aria about Exceptions — try/except/else/finally

Your personal AI tutor — ask anything about this concept

Revision Status

Personal Notes

Sign in to save personal notes for this topic.

Discussion

Sign in to join the discussion.

Loading discussion…