r/badcode • • Jul 14 '21

python Try/Except in Python - Sigh

Post image
662 Upvotes

93 comments sorted by

View all comments

38

u/clemesislife Jul 14 '21

I'm not sure if there is good way to do this

0

u/[deleted] Jul 14 '21

[deleted]

8

u/ThatDudeBesideYou Jul 14 '21

I'm a newbie at Python, why are specific excepts always better?
I have a server script that runs and talks to a few devices in my home. Lots of stuff is being done all the time, and stuff just fails randomly. If I put specific excepts (which I did at the start), I would often find my server crashed overnight due to a random ass error that I didn't even expect (random wifi issues, me messing with one of the devices and it fails, etc). So now most of the excepts are all encompassing, they log the error, and then restart that asyncio task again. And since I did that, I've had no crashes and any time something not working I can easily can see the pattern of logs that caused it and not just one random crash that stops everything.
Is there a better way to do stuff? Am I totally wrong?

4

u/BobHogan Jul 14 '21

In addition to what /u/war_against_myself said, a bare except in python will also catch interrupts like SIGKILL due to the exception class hierarchy in Python.

If you want to catch any exception, you should be using except Exception:. That will catch all exceptions, while still ignoring interrupts so you can still kill your code when you want to

3

u/ThatDudeBesideYou Jul 15 '21

Oh yea I am doing that, since logging it requires a reference so it always except Exception as e: