How to Properly Catch and Raise Exceptions
π How to Properly Catch and Raise Exceptions β A Guide for Junior Developers
(This article was created by Qwen AI)
Handling exceptions correctly isn’t just about preventing crashes β it makes your code more stable, easier to debug, and simpler to maintain. Here are simple, practical rules every junior developer should follow.
1 β Only catch an exception when you know what to do
β Don’t catch an exception just “because you can”.
|
|
β Only catch it if you can handle it meaningfully:
|
|
2 β If you only log, then re-raise the exception
When you’re in a low-level function (e.g., writing to a file, calling an API), you might want to log the error for debugging, but if you can’t fully handle it, you must re-raise.
|
|
πΉ Using
raise
(without arguments) preserves the original traceback β very helpful for debugging later.
3 β Handle errors where you have enough context
β Higher-level functions (like
a()
) are usually closest to the user, so they’re the best place to:
- Show user-friendly error messages.
- Suggest actions (retry, check permissions, etc.).
- Log high-level system events.
|
|
4 β When should you NOT re-raise?
Only when youβve fully resolved the issue and the program can safely continue:
|
|
β In this case, the error is not a failure β it’s part of a valid execution path.
5 π« What you should NOT do
- β Catch an exception and just
pass
or useraise Exception("...")
(this loses the traceback). - β Catch the same error at multiple levels without adding value.
- β Log and then stay silent β if you can’t handle it, donβt hide it.
6 π‘ The 3 Golden Rules
- Donβt catch if you donβt know what to do.
- Logged the error? Still
raise
if itβs not fully handled. - Handle the error where you have user or system context.
π Remember: Exceptions are not bad β what matters is that you handle them responsibly.
β Written by a dev who once swallowed an exception and spent 3 hours debugging π