Python try except

Learn how Python try except works with simple examples. See how to catch specific exceptions, handle multiple exceptions, use else and finally, raise exceptions, and avoid common mistakes.

Published

Updated

Read time 8 min read

Reviewed byDeepak Prasad

Python try except

Python does not use try catch. In Python, the syntax is try except. Put risky code inside try, then handle the error inside except.

Use try for code that may fail. Use except to handle the exception so the program does not stop unexpectedly. Python's official tutorial explains that the try clause runs first; if an exception occurs, Python looks for a matching except clause, and if no exception occurs, the except clause is skipped.

Tested on: Python 3.13.3; kernel 6.14.0-37-generic.


Python try except quick reference

Task Syntax / keyword
Catch one specific error except ValueError:
Catch multiple errors together except (ValueError, TypeError):
Get the error message except ValueError as e:
Run code only when no error occurs else:
Always run cleanup code finally:
Raise an error manually raise ValueError("message")
Re-raise the same exception raise
Python equivalent of try catch try except

Basic try except syntax in Python

  • The try block contains code that may raise an exception.
  • The except block handles a matching exception.
  • If no exception occurs, except is skipped.
  • If an exception occurs and matches the except block, Python runs that handler.
python
try:
    age = int("abc")
except ValueError:
    print("Please enter a valid number.")
Output

Invalid text for int() raises ValueError, and the handler prints a friendly message instead of stopping the program.

python
try:
    result = 10 / 0
except ZeroDivisionError:
    print("You cannot divide by zero.")
Output

Division by zero raises ZeroDivisionError, which the second handler catches.


Python try catch equivalent

Python does not use catch. The equivalent of try-catch in Java, JavaScript, C#, or PHP is try except in Python.

Other languages Python
try { ... } catch (err) { ... } try: ... except Exception as err: ...

If you searched for python try catch or try catch python, you want except, not catch.


Catch a specific exception

Prefer catching specific exceptions. They make debugging easier and keep handlers focused.

python
user_text = "twenty"

try:
    count = int(user_text)
except ValueError:
    print("Not a valid integer.")
Output
python
try:
    average = 100 / 0
except ZeroDivisionError:
    print("Division by zero is not allowed.")
Output
python
try:
    with open("missing_file.txt", "r") as f:
        data = f.read()
except FileNotFoundError:
    print("That file does not exist.")
Output
python
scores = {"math": 90, "science": 85}

try:
    print(scores["english"])
except KeyError:
    print("That key is not in the dictionary.")
Output

Common pairings: ValueError for bad conversions, ZeroDivisionError for divide-by-zero, FileNotFoundError for missing files, and KeyError for missing dictionary keys.


Catch multiple exceptions

Use a tuple of exception classes when different errors can be handled the same way:

python
text = "abc"
divisor = 0

try:
    number = int(text)
    result = 10 / number
except (ValueError, ZeroDivisionError):
    print("Invalid number or division by zero.")
Output

Use separate except blocks when each error needs a different message or action:

python
text = "abc"

try:
    number = int(text)
    result = 10 / number
except ValueError:
    print("Enter a valid integer.")
except ZeroDivisionError:
    print("Cannot divide by zero.")
Output

See catch multiple exceptions for more patterns.


Use except Exception as e

as e stores the exception object—useful for logging or showing a message:

python
try:
    value = int("not-a-number")
except ValueError as e:
    print(f"Conversion failed: {e}")
Output

except Exception catches most normal program errors. It does not catch BaseException subclasses such as KeyboardInterrupt and SystemExit, so Ctrl+C and sys.exit() still behave as expected.

Use a broad except Exception as e handler when you need a fallback, but prefer specific exceptions when you know what can fail.


Bare except vs except Exception

A bare except: catches too much, including KeyboardInterrupt and SystemExit. Avoid it in normal application code.

python
# Avoid
try:
    risky()
except:
    pass
Output

Prefer a specific type or Exception:

python
try:
    value = int("x")
except ValueError as e:
    print(f"Bad input: {e}")
Output

Use bare except only in rare cases where you intentionally need to catch everything—and even then, log or re-raise when possible.


Use else with try except

The else block runs only if the try block does not raise an exception. Put success-only code there so the try block stays small.

python
text = "8"

try:
    number = int(text)
except ValueError:
    print("Invalid input.")
else:
    result = 10 / number
    print(f"Result: {result}")
Output

Conversion happens in try; division runs in else only after a successful conversion.


Use finally with try except

The finally block always runs, whether or not an exception occurred. It is useful for cleanup such as releasing locks or closing connections.

python
try:
    print("Opening resource...")
    raise ValueError("Something went wrong")
except ValueError:
    print("Handled the error.")
finally:
    print("Cleanup always runs.")
Output

Both handler and cleanup messages print.

When reading files, prefer with open(...) instead of manual finally just to close the file—the context manager closes it for you:

python
try:
    with open("data.txt", "r") as f:
        print(f.read())
except FileNotFoundError:
    print("File not found.")
Output

See writing and reading files for file patterns.


Raise an exception manually

Use raise to signal an error intentionally—common for input validation or bad function arguments:

python
def validate_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative.")
    return age

try:
    validate_age(-5)
except ValueError as e:
    print(e)
Output

Use built-in exceptions such as ValueError or TypeError when they describe the problem clearly.


Re-raise an exception

Use plain raise inside except to re-raise the same exception after logging or partial handling:

python
def validate_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative.")
    return age

try:
    validate_age(-5)
except ValueError as e:
    print(f"Logged: {e}")
    raise

The error is logged, then propagated to the caller. Re-raise when you cannot fully recover but still want a record of what happened.


Nested try except in Python

A nested try except places one block inside another. Use it when inner and outer operations need separate handling—but separate functions are often cleaner than deep nesting.

python
outer_text = "5"
inner_text = "0"

try:
    x = int(outer_text)
    try:
        y = int(inner_text)
        print(x / y)
    except ZeroDivisionError:
        print("Inner: cannot divide by zero.")
except ValueError:
    print("Outer: enter a valid number.")
Output

The outer block handles bad outer input; the inner block handles division by zero.


Common Python exceptions

Exception Common cause
ValueError Correct type but invalid value
TypeError Operation used with wrong type
ZeroDivisionError Division by zero
FileNotFoundError File path does not exist
KeyError Dictionary key missing
IndexError List/tuple index out of range
AttributeError Attribute or method does not exist
ImportError / ModuleNotFoundError Import failed
PermissionError No permission for file or OS operation

For the full hierarchy, see the Python built-in exceptions docs.


try except in real examples

Convert user input to int safely

python
raw = "42"

try:
    age = int(raw)
except ValueError:
    age = None

print(age)
Output

With valid digits, age is an integer; invalid text sets age to None. For interactive user input, wrap int(input(...)) the same way.

Handle a missing file

python
filename = "report.txt"

try:
    with open(filename, "r") as f:
        content = f.read()
except FileNotFoundError:
    content = ""
    print("Using empty default.")
Output

Handle a dictionary key error

python
user = {"name": "Alice", "role": "admin"}

try:
    department = user["department"]
except KeyError:
    department = "Unknown"
Output

Handle division by zero

python
def safe_divide(a, b):
    try:
        return a / b
    except ZeroDivisionError:
        return None

print(safe_divide(10, 2))
print(safe_divide(10, 0))
Output

The first call returns 5.0; the second returns None.

Validate function arguments with raise

python
def set_discount(percent):
    if not 0 <= percent <= 100:
        raise ValueError("Discount must be between 0 and 100.")
    return percent

try:
    set_discount(150)
except ValueError as e:
    print(e)
Output

Handle a network request error

python
import urllib.request
import urllib.error

url = "https://example.com"

try:
    with urllib.request.urlopen(url, timeout=5) as response:
        print(response.status)
except urllib.error.URLError as e:
    print(f"Request failed: {e}")

Network and timeout failures belong in try except; use {run=false} when the example depends on live network access.


try except vs if else

Situation Prefer
You can check a condition clearly first if else
The operation may fail during execution try except
python
# Clear condition — if is fine
if divisor == 0:
    print("Cannot divide by zero.")
else:
    print(10 / divisor)
Output
python
# Conversion may fail — try except is natural
try:
    number = int(text)
except ValueError:
    number = None
Output

Do not use exceptions for normal routine control flow when a simple if / else condition is clearer.


Best practices for Python try except

  • Catch specific exceptions whenever possible.
  • Keep try blocks small—only the code that can fail.
  • Do not hide errors with empty except blocks.
  • Use else for code that should run only on success.
  • Use finally for cleanup when a context manager is not enough.
  • Log exceptions with useful context—see Python logging.
  • Avoid bare except unless you have a deliberate reason.
  • Do not catch exceptions you cannot handle meaningfully—let them propagate or fail fast.

Mistakes to avoid

  1. Writing try catch instead of try except — Python's keyword is except.
  2. Using except: pass — silent failures are hard to debug.
  3. Catching Exception too early — handle specific errors first, generic handlers last.
  4. Putting too much code inside try — narrow the block to the risky line(s).
  5. Using the same generic message for every error — different failures often need different responses.
  6. Expecting try except to fix syntax errors — invalid Python syntax is caught at parse time, not inside a runtime handler around broken code.
  7. Using finally only to close files — prefer with open(...) when possible.
  8. Catching an error and continuing with invalid data — set a safe default or stop when recovery is not possible.

Summary

Python uses try except, not try catch. The try block holds code that may fail; except handles matching exceptions; else runs only when no exception occurs; finally always runs and is useful for cleanup. Catch specific exceptions whenever you can, keep try blocks small, and use raise when your code needs to signal an error on purpose.

Useful references


Frequently Asked Questions

1. Does Python use try catch or try except?

Python uses try except, not try catch. Put code that may fail inside try, then handle the matching error inside except.

2. What is the difference between else and finally in try except?

The else block runs only when the try block finishes without an exception. The finally block always runs, whether or not an exception occurred—useful for cleanup.

3. Should I use except Exception as e?

Use except Exception as e when you need a broad fallback handler for logging or a generic message. Prefer specific exceptions such as ValueError or FileNotFoundError when you know what can fail.

4. What is wrong with a bare except clause?

A bare except catches too much, including KeyboardInterrupt and SystemExit. Prefer except SpecificError or except Exception as e instead of except: alone.

5. When should I use try except instead of if else?

Use if else when you can check a condition clearly before acting. Use try except when an operation may fail during execution, such as int conversion, file access, or division.

6. How do I catch multiple exceptions in Python?

Use a tuple in one except block, such as except (ValueError, TypeError):, or use separate except blocks when each error needs a different response.
Bashir Alam

Data Analyst and Machine Learning Engineer

Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in OCR, text extraction, data preprocessing, and …