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
tryblock contains code that may raise an exception. - The
exceptblock handles a matching exception. - If no exception occurs,
exceptis skipped. - If an exception occurs and matches the
exceptblock, Python runs that handler.
try:
age = int("abc")
except ValueError:
print("Please enter a valid number.")Invalid text for int() raises ValueError, and the handler prints a friendly message instead of stopping the program.
try:
result = 10 / 0
except ZeroDivisionError:
print("You cannot divide by zero.")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.
user_text = "twenty"
try:
count = int(user_text)
except ValueError:
print("Not a valid integer.")try:
average = 100 / 0
except ZeroDivisionError:
print("Division by zero is not allowed.")try:
with open("missing_file.txt", "r") as f:
data = f.read()
except FileNotFoundError:
print("That file does not exist.")scores = {"math": 90, "science": 85}
try:
print(scores["english"])
except KeyError:
print("That key is not in the dictionary.")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:
text = "abc"
divisor = 0
try:
number = int(text)
result = 10 / number
except (ValueError, ZeroDivisionError):
print("Invalid number or division by zero.")Use separate except blocks when each error needs a different message or action:
text = "abc"
try:
number = int(text)
result = 10 / number
except ValueError:
print("Enter a valid integer.")
except ZeroDivisionError:
print("Cannot divide by zero.")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:
try:
value = int("not-a-number")
except ValueError as e:
print(f"Conversion failed: {e}")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.
# Avoid
try:
risky()
except:
passPrefer a specific type or Exception:
try:
value = int("x")
except ValueError as e:
print(f"Bad input: {e}")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.
text = "8"
try:
number = int(text)
except ValueError:
print("Invalid input.")
else:
result = 10 / number
print(f"Result: {result}")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.
try:
print("Opening resource...")
raise ValueError("Something went wrong")
except ValueError:
print("Handled the error.")
finally:
print("Cleanup always runs.")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:
try:
with open("data.txt", "r") as f:
print(f.read())
except FileNotFoundError:
print("File not found.")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:
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)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:
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}")
raiseThe 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.
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.")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
raw = "42"
try:
age = int(raw)
except ValueError:
age = None
print(age)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
filename = "report.txt"
try:
with open(filename, "r") as f:
content = f.read()
except FileNotFoundError:
content = ""
print("Using empty default.")Handle a dictionary key error
user = {"name": "Alice", "role": "admin"}
try:
department = user["department"]
except KeyError:
department = "Unknown"Handle division by zero
def safe_divide(a, b):
try:
return a / b
except ZeroDivisionError:
return None
print(safe_divide(10, 2))
print(safe_divide(10, 0))The first call returns 5.0; the second returns None.
Validate function arguments with raise
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)Handle a network request error
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 |
# Clear condition — if is fine
if divisor == 0:
print("Cannot divide by zero.")
else:
print(10 / divisor)# Conversion may fail — try except is natural
try:
number = int(text)
except ValueError:
number = NoneDo 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
tryblocks small—only the code that can fail. - Do not hide errors with empty
exceptblocks. - Use
elsefor code that should run only on success. - Use
finallyfor cleanup when a context manager is not enough. - Log exceptions with useful context—see Python logging.
- Avoid bare
exceptunless you have a deliberate reason. - Do not catch exceptions you cannot handle meaningfully—let them propagate or fail fast.
Mistakes to avoid
- Writing
try catchinstead oftry except— Python's keyword isexcept. - Using
except: pass— silent failures are hard to debug. - Catching
Exceptiontoo early — handle specific errors first, generic handlers last. - Putting too much code inside
try— narrow the block to the risky line(s). - Using the same generic message for every error — different failures often need different responses.
- Expecting
try exceptto fix syntax errors — invalid Python syntax is caught at parse time, not inside a runtime handler around broken code. - Using
finallyonly to close files — preferwith open(...)when possible. - 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

