Is it a good practice to use try-except-else in Python?

后端 未结 10 2081
情深已故
情深已故 2020-11-22 13:50

From time to time in Python, I see the block:

try:
   try_this(whatever)
except SomeException as exception:
   #Handle exception
else:
   return something
         


        
10条回答
  •  眼角桃花
    2020-11-22 14:15

    OP, YOU ARE CORRECT. The else after try/except in Python is ugly. it leads to another flow-control object where none is needed:

    try:
        x = blah()
    except:
        print "failed at blah()"
    else:
        print "just succeeded with blah"
    

    A totally clear equivalent is:

    try:
        x = blah()
        print "just succeeded with blah"
    except:
        print "failed at blah()"
    

    This is far clearer than an else clause. The else after try/except is not frequently written, so it takes a moment to figure what the implications are.

    Just because you CAN do a thing, doesn't mean you SHOULD do a thing.

    Lots of features have been added to languages because someone thought it might come in handy. Trouble is, the more features, the less clear and obvious things are because people don't usually use those bells and whistles.

    Just my 5 cents here. I have to come along behind and clean up a lot of code written by 1st-year out of college developers who think they're smart and want to write code in some uber-tight, uber-efficient way when that just makes it a mess to try and read / modify later. I vote for readability every day and twice on Sundays.

提交回复
热议问题