Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic Exception Handling in Python the "Right Way"

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?

like image 675
Sufian Avatar asked Sep 24 '08 19:09

Sufian


People also ask

How does Python handle generic exceptions?

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.

How do you handle generic exceptions?

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.

Which one of the following is the correct exception of the Python file?

py Explanation: ". py" is the correct extension of the Python file.

How many ways can you handle exceptions in Python?

When a Python code throws an exception, it has two options: handle the exception immediately or stop and quit.


1 Answers

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) 
like image 163
Ryan Avatar answered Oct 17 '22 23:10

Ryan