Bad idea to catch all exceptions in Python

Why is it a bad idea to catch all exceptions in Python?

I understand that catching all exceptions with the except: clause will even catch the “special” python exceptions: SystemExit , KeyboardInterrupt and GeneratorExit . So, why not just use the except Exception: clause to catch all the exceptions?

+7
source share
2 answers

Because it is terribly non-specific, and it does not allow you to do anything interesting with the exception. Moreover, if you catch every exception, there can be many exceptions that occur that you don’t even know what is happening (which could lead to your application crashing if you really don’t know why). You should be able to predict (either through reading documentation or experimenting) which particular exceptions you should handle and how to handle them, but if you blindly suppress all of them from the very beginning, you will never know.

So, for a popular query, here is an example. The programmer writes Python code and it receives an IOError . Instead of investigating further, she resolves all the exceptions:

 def foo(): try: f = open("file.txt") lines = f.readlines() return lines[0] except: return None 

She does not understand the question in her own way: what if the file exists and is accessible, but it is empty? Then this code will raise an IndexError (since the lines list is empty). Therefore, she will spend hours pondering why she gets None back from this function when the file exists and is not locked, not understanding what would be obvious if it were more specific in detecting errors, namely, that it accesses the data, which may not exist.

+20
source

Because you probably want to handle each exception differently. This is not the same as KeyInterrupt than an encoding problem or one OS ... You can track specific exceptions one by one.

 try: XXX except TYPE: YYY except TYPE: ZZZ 
+3
source

All Articles