try/except in Python
Why use try/except?
Section titled “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
Section titled “Basic try/except”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
Section titled “Catch specific exceptions”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
Section titled “Catch multiple exception types”try:
x = int(input("Enter a number: "))
print(10 / x)
except (ValueError, ZeroDivisionError) as e:
print("Error:", e)Capture the exception object
Section titled “Capture the exception object”try:
int("abc")
except ValueError as e:
print("Type:", type(e))
print("Message:", e)Best practices
Section titled “Best practices”- Catch the narrowest exception you can.
- Don’t silently ignore exceptions.
- Log exceptions in production systems.
- Avoid
except Exception:unless you re-raise or report clearly.
Visualize it
Section titled “Visualize it”try / except / else / finally is a small decision tree. Python runs the try body; if an
exception is raised it jumps to a matching except; the else runs only when no
exception occurred; and finally 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
Section titled “🧪 Try It Yourself”Exercise 1 – Catch a ValueError
Section titled “Exercise 1 – Catch a ValueError”Exercise 2 – Multiple Except Blocks
Section titled “Exercise 2 – Multiple Except Blocks”Exercise 3 – Raise a Custom Exception
Section titled “Exercise 3 – Raise a Custom Exception”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading