Robust code cries often and loudly as soon as something is not right. It does not cower away in corners of obscurity hoping that no one will notice, until one day, shit hits the fan.
Any serious python code contains proper use of exceptions
, and asserts
. In fact, I would argue that their presence defines the difference between one-off throwaway scripts and robust library code.
Imagine a python interpreter without these facilities. What would the scenario look like?
When you write to a non-existent or write-protected file, instead of the sys
module alerting you to the fact, you'd get .. nothing
. Not a single sign that your data is gone forever.
Exceptions are you friends. They're your canary in the coal mine. They let you know that something is wrong at the point of inception rather than pretending that everything is fine until two months later when your client pops a vein because their files were not backed-up.
to annotate your code. Use them to communicate to your future colleagues that what they're trying to do is seriously wrong. Use them to put yourself in check before you try to modify that class attribute. Exceptions
keep you sane.
Some would argue that robust code has no exceptions
in it. They would be happy to throw a giant all-inclusive try ... except
statement around every piece of code that raises an exception. Don't do it, please. That's like ignoring a crying kid without knowing why they are crying in the first place.
Here's a simple rule of thumb for dealing with exceptions -- I guess you can call it a best-practice. Catch specific
exceptions and errors only if you know what to do with them
. Otherwise, let some other piece of code higher in the call stack with enough context deal with it.
Robust code cries often and loudly as soon as something is not right. It does not cower away in corners of obscurity hoping that no one will notice, until one day, shit hits the fan. At the same time, when it knows how to deal with an exception, it'll do so. But it will never
suppress an exception when it has no idea.
and Exception Handlers
. These are the two pillars of robust, high-quality, and fault-tolerant code.