Sometimes I find myself in the situation where I want to execute several sequential commands like such:
try: foo(a, b) except Exception, e: baz(e) try: bar(c, d) except Exception, e: baz(e) ...
This same pattern occurs when exceptions simply need to be ignored.
This feels redundant and the excessive syntax causes it to be surprisingly difficult to follow when reading code.
In C, I would have solved this type of problem easily with a macro, but unfortunately, this cannot be done in straight python.
Question: How can I best reduce the code footprint and increase code readability when coming across this pattern?
You can also provide a generic except clause, which handles any exception. After the except clause(s), you can include an else-clause. The code in the else-block executes if the code in the try: block does not raise an exception. The else-block is a good place for code that does not need the try: block's protection.
The generic exception handler can handle all the exceptions but you should place is at the end, if you place it at the before all the catch blocks then it will display the generic message. You always want to give the user a meaningful message for each type of exception rather then a generic message.
py Explanation: ". py" is the correct extension of the Python file.
When a Python code throws an exception, it has two options: handle the exception immediately or stop and quit.
You could use the with
statement if you have python 2.5 or above:
from __future__ import with_statement import contextlib @contextlib.contextmanager def handler(): try: yield except Exception, e: baz(e)
Your example now becomes:
with handler(): foo(a, b) with handler(): bar(c, d)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With