In python is it true that except Exception as ex
or except BaseException as ex
is the the same as except:
but you get a reference to the exception?
From what I understand BaseException
is the newer default catch-all.
Aside from that why would you ever want just an except:
clause?
The difference between the three is:
except
catches everything, including system-exiting things like KeyboardInterrupt
;except Exception[ as ex]
will catch any subclass of Exception
, which should be all your user-defined exceptions and everything built-in that is non-system-exiting; andexcept BaseException[ as ex]
will, like bare except
, catch absolutely everything.Generally, I would recommend using 2. (ideally as a fallback, after you have caught specific/"expected" errors), as this allows those system-exiting exceptions to percolate up to the top level. As you say, the as ex
part for 2. and 3. lets you inspect the error while handling it.
There is a useful article on "the evils of except" here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With