Error Handling and Exceptions

Unspecified error handling should rarely be used:


try:
   ...
except:
   ...

It catches ALL errors. This construct is viable when you want to explicitly encapsulate the surrounded code. You have to be aware you need to deal with ALL these different errors - even errors you do not think about. In most cases it means you have to treat them all the same. There are use cases to it, e.g. to close a connection or roll back a transaction. It should not be uses just because you can.

The “pass” in the unspecified except clause is evil!

Why? Because it hides any error without dealing with it. This makes it nearly impossible to maintain the surrounded code as there is no information that errors happened or not. Imagine there is an AttributeError. You would not notice that you mistyped the attribute.

Better specify the error:


try:
   ...
except KeyError:
   pass # explicitly do not care if the key exists or not

It is valid to use “pass” on specific errors e.g. when KeyError. The code explicitly says: “yes, I know this error. When it happens I will not do anything and just go on”. The

In general I recommend to mention any expected error you expect. This way any unexpected error will be passed to the code layer above. Additional the code tells what you expect can happen beside the “good case”.