Jul
21
How to handle exceptions
Earlier today, I saw two different StackOverflow questions that basically looked like this:
Why does this not work? try: [broken code] except: print('[-] exception occurred') Unless someone can read minds or gets lucky or puts a whole lot more work into your question than you have any right to expect, the only answer anyone can give is "because an exception occurred", because your code goes out of its way to make it impossible for you to tell us what exception occurred and why.
This is exactly why you almost never want to handle exceptions with a bare except clause.
So, how do you want to handle exceptions?
If there's a specific exception you want to deal with, handle that
On both posts, someone suggested replacing the except: with except Exception:.
Why does this not work? try: [broken code] except: print('[-] exception occurred') Unless someone can read minds or gets lucky or puts a whole lot more work into your question than you have any right to expect, the only answer anyone can give is "because an exception occurred", because your code goes out of its way to make it impossible for you to tell us what exception occurred and why.
This is exactly why you almost never want to handle exceptions with a bare except clause.
So, how do you want to handle exceptions?
If there's a specific exception you want to deal with, handle that
On both posts, someone suggested replacing the except: with except Exception:.