Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In python why ever use except:

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?

like image 202
atxdba Avatar asked Dec 06 '22 02:12

atxdba


1 Answers

The difference between the three is:

  1. bare except catches everything, including system-exiting things like KeyboardInterrupt;
  2. 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; and
  3. except 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.

like image 106
jonrsharpe Avatar answered Dec 30 '22 21:12

jonrsharpe