Python try except for controlled error handling
Python try except handles runtime errors so the program can continue with a fallback. Use it when parsing user input or reading a file might fail but the rest of the work should still run. The key is to wrap only the risky lines, catch the expected exception, and provide a safe default.
Python Try Except Example For Error Handling
Output:
Output will appear here...
Output:
0
How This Example Works
- The
tryblock attempts to convert the text to an integer. - When
int()fails, theexcept ValueErrorblock assigns a fallback value. - The
printruns after the block, so the script always outputs a usable number. - The output shows the fallback path, which proves the error was handled instead of crashing.
Common Mistakes with Python try except
Mistake 1: Catching everything with a bare except.
try:
total = int(text)
except:
total = 0
try:
total = int(text)
except ValueError:
total = 0
Why it happens: a bare except catches system-exiting errors like KeyboardInterrupt and SystemExit, making programs harder to stop and debug. Prefer the specific exception you expect.
Mistake 2: Putting too much code inside try and hiding unrelated bugs.
total = 10
try:
count = int(text)
ratio = total / count
except Exception:
ratio = 0
total = 10
try:
count = int(text)
except ValueError:
ratio = 0
else:
ratio = total / count
Why it happens: broad handlers can mask errors from lines that should fail loudly. The else block runs only when no exception occurs, so unexpected bugs do not get swallowed.
Mistake 3: Ordering except blocks from broad to specific.
try:
count = int(text)
except Exception:
count = 0
except ValueError:
count = 0
try:
count = int(text)
except ValueError:
count = 0
except Exception:
count = 0
Why it happens: Python picks the first matching handler, so a broad exception placed first makes the specific one unreachable.
Performance Considerations
A try block with no exception is efficient, but raising and catching exceptions is relatively expensive. If failures are expected as part of normal flow, a simple pre-check (like validating input) can be faster and clearer. When failures are truly exceptional, try and except keeps the happy path readable without a meaningful performance cost.
When to Use try except
- Use it when an operation can fail and you have a safe fallback (parsing text, reading a file, or calling an API).
- Use it to keep batch work moving by skipping bad items while logging the error you handled.
- Keep the
tryblock tight so only the risky line is protected and other bugs still surface. - Avoid it when failure is the normal path and a simple condition is cheaper and clearer.
- Avoid catching
BaseExceptionor a genericExceptionunless you re-raise or log with intent.