try/except in Python
Why use try/except?
Exceptions are normal in real programs:
- network failures
- missing files
- invalid user input
Instead of crashing, you can handle the problem and continue.
Basic try/except
basic_try_except.py
try:
x = int(input("Enter a number: "))
print(10 / x)
except Exception:
print("Something went wrong")basic_try_except.py
try:
x = int(input("Enter a number: "))
print(10 / x)
except Exception:
print("Something went wrong")This works, but it’s usually too broad.
Catch specific exceptions
specific_excepts.py
try:
x = int(input("Enter a number: "))
print(10 / x)
except ValueError:
print("Please enter only digits.")
except ZeroDivisionError:
print("Number can’t be 0.")specific_excepts.py
try:
x = int(input("Enter a number: "))
print(10 / x)
except ValueError:
print("Please enter only digits.")
except ZeroDivisionError:
print("Number can’t be 0.")Catch multiple exception types
multi_except.py
try:
x = int(input("Enter a number: "))
print(10 / x)
except (ValueError, ZeroDivisionError) as e:
print("Error:", e)multi_except.py
try:
x = int(input("Enter a number: "))
print(10 / x)
except (ValueError, ZeroDivisionError) as e:
print("Error:", e)Capture the exception object
exception_object.py
try:
int("abc")
except ValueError as e:
print("Type:", type(e))
print("Message:", e)exception_object.py
try:
int("abc")
except ValueError as e:
print("Type:", type(e))
print("Message:", e)Best practices
- Catch the narrowest exception you can.
- Don’t silently ignore exceptions.
- Log exceptions in production systems.
- Avoid
except Exception:except Exception:unless you re-raise or report clearly.
Visualize it
try / except / else / finallytry / except / else / finally is a small decision tree. Python runs the trytry body; if an
exception is raised it jumps to a matching exceptexcept; the elseelse runs only when no
exception occurred; and finallyfinally always runs, error or not:
flowchart TD
A([Enter try]) --> B["Run try body"]
B --> C{"Exception raised?"}
C -- yes --> D["Run matching except"]
C -- no --> E["Run else block"]
D --> F["Run finally (always)"]
E --> F
F --> G([Continue])
🧪 Try It Yourself
Exercise 1 – Catch a ValueError
Exercise 2 – Multiple Except Blocks
Exercise 3 – Raise a Custom Exception
If this helped you, consider buying me a coffee ☕
Buy me a coffeeWas this page helpful?
Let us know how we did
