Originally Posted by denisT
i know how try statement works (c++, c#, python, maxscript, ...) but if you don't know the system very well it might hide from you the real reason of an exception. <....> try/catch statement is kinda last in list of solutions
I might be late to the discussion, but exception handling code is a first-class flow control form, just like an "if" or "for" blocks. Performance wise you won't get any real benefit, you'll just write "if exists then... " instead of "assume it exists, handle it if it goes wrong".
about hiding the reason of the exception... that's totally not true. exception handling gives great control of information why something failed, and how to control specific types of exceptional cases, like "if user supplied arguments were wrong, do this, and if we have unforseen internal problem during execution, do this".
Your story about whiskey is not how exception handling works, it's more how API that throws no error works - it fails, but does not report the problem. In exception handling case, it would be:
except OutOfStockException as e:
print "damn, there was no stock of "+e.item
except IllegalAgeException as e:
print "damn, I must be %s to order %s" % (e.legealAge,e.drinkType)
except RestaurantPolicyException as e:
print "I was not served because "+str(e)
except BaseException as e:
throw IllegalStateException("unforseen problems during restaurant visit: "+str(e))
.. so you can be as verbose as you'd like, maybe you only want to handle one situation, have a default handler for any exception, or rethrow for outside flow to handle. in fact, leaving exceptions for outer flow to handle is the most overlooked use case for those still trying to understand the real benefits of the system. Or catch - provide own implementation of recovery - rethrow for outer flow to handle it's own bit..
not using exception handling in your arsenal is one step away from not using.. don't know, objects and polymorphism, because you've heard that in this other language virtual function table is a lot of overhead! yes, it is, but it does not matter in Python