Skip to main content
  • Python is available now. All other compilers are coming soon.

    Python
  • Popular Tutorials

    • Getting Started With Python
    • Python if Statement
    • while Loop in Python
    • Python Lists
    • Dictionaries in Python
    All Python Tutorials

    Reference Materials

    Built-in FunctionsList MethodsDictionary MethodsString Methods
    View all

Online Compilers

  • Python Compiler
  • Python Playground
  • Python Projects
  • Exercises

Tutorials

  • Learn Python
  • Python for Beginners
  • Variables and Types
  • Python Strings
  • Python Lists
  • Python If Else
  • Python For Loops
  • Python Functions
  • Python Classes

Examples

  • Python Examples
  • Hello World
  • Add Two Numbers
  • Even or Odd
  • Factorial
  • Fibonacci
  • Prime Check
  • Palindrome Check

Company

  • About
  • Contact
  • Privacy Policy
  • Terms of Use
  • Disclaimer

© 2026 ILoveCompiler. All rights reserved.

  1. Home
  2. Python Tutorial
  3. Python Error Handling with try, except, else, and finally

Working with Python · Tutorial 22

Python Error Handling with try, except, else, and finally

Read tracebacks, catch specific exceptions, raise your own errors, and clean up resources reliably.

Open the compilerPractice exercises
intermediate9 min readUpdated November 19, 20264 learning goals
On this page
  1. Reading a traceback
  2. Catching exceptions
  3. Multiple except blocks
  4. Raising exceptions
  5. finally for cleanup
  6. Custom exceptions
  7. Practice

What you will learn

  • Read a traceback from top to bottom
  • Catch specific exceptions with try and except
  • Use else and finally correctly
  • Raise ValueError for invalid arguments
Before this lesson: Python Functions: Define, Call, and Return Values, Python Variable Scope and Object Lifetime

Errors are part of normal programming. Some errors are syntax problems that prevent the file from running; others happen while the program executes.

Reading a traceback#

Python
number = int("abc")
Expected output

Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: 'abc'

Read the last line first: it names the exception and gives a short explanation. The lines above show the call path. In ILoveCompiler, the Errors panel presents the traceback with the same information.

Catching exceptions#

Python
text = input("Enter a number: ")

try:
    number = int(text)
except ValueError:
    print("That is not a whole number.")
else:
    print(f"Doubled: {number * 2}")
  • The try block contains code that may fail.
  • except ValueError handles only that exception type.
  • else runs when no exception occurred.
  • finally always runs, whether or not an exception was raised.

Catch specific exceptions. A bare except: also catches KeyboardInterrupt and SystemExit, which usually should not be swallowed.

Python
try:
    value = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")

Multiple except blocks#

Python
try:
    number = int(input())
    result = 100 / number
except ValueError:
    print("Please enter a whole number")
except ZeroDivisionError:
    print("The number cannot be zero")

Python checks the handlers in order and runs the first matching one.

You can capture the exception object:

Python
try:
    number = int("abc")
except ValueError as error:
    print("Conversion failed:", error)

Use the message for logging or diagnostics. Do not display raw technical details to end users unless the context is appropriate.

Raising exceptions#

When a function receives invalid input, raise an exception instead of returning a misleading value:

Python
def set_age(age):
    if not isinstance(age, int):
        raise TypeError("age must be an integer")
    if age < 0 or age > 150:
        raise ValueError("age must be between 0 and 150")
    return age

The caller can handle these errors:

Python
try:
    set_age(200)
except ValueError as error:
    print(error)
Expected output

age must be between 0 and 150

finally for cleanup#

finally is useful when a resource must be released:

Python
def read_first_line(path):
    file = open(path, encoding="utf-8")
    try:
        return file.readline().strip()
    finally:
        file.close()

The file closes even if reading raises. For most file work, a with statement is shorter and safer:

Python
with open("notes.txt", encoding="utf-8") as file:
    first_line = file.readline().strip()

The context manager closes the file automatically, including when an exception occurs.

Custom exceptions#

Larger programs define exception classes to represent domain failures:

Python
class InsufficientFundsError(Exception):
    """Raised when a withdrawal exceeds the available balance."""


def withdraw(balance, amount):
    if amount > balance:
        raise InsufficientFundsError("Not enough funds")
    return balance - amount

A specific class lets callers distinguish this failure from unrelated errors.

Do not hide bugs

Avoid wrapping an entire program in try/except Exception: pass. It silences genuine mistakes and makes debugging nearly impossible. Catch only what you can handle meaningfully.

Practice#

Write a program that repeatedly asks for two integers and prints their quotient. Handle ValueError and ZeroDivisionError separately. Add a finally block that prints "Attempt finished". Then write a function that raises ValueError when a score is outside 0 to 100.

Previous tutorialPython Variable Scope and Object LifetimeNext tutorialPython Classes and Objects: A Practical Introduction

Related tutorials

intermediate

Python Classes and Objects: A Practical Introduction

Define classes, create objects, use __init__ and methods, and model state without overengineering.

10 min read
beginner

Reading User Input with Python input()

Read text and numbers from standard input, understand prompts, and design programs that handle supplied input cleanly.

7 min read

On this page

  1. Reading a traceback
  2. Catching exceptions
  3. Multiple except blocks
  4. Raising exceptions
  5. finally for cleanup
  6. Custom exceptions
  7. Practice

Run the examples

Every Python block has a Run in compiler button that opens the code in a new tab.