I have got a project, where I have to do this very frequently:
if "something" in dict:
some_var = dict["something"]
del dict["something"]
else:
error_handler_or_other_stuff()
However I have the idea to use this:
try:
some_var = dict.pop("something")
except KeyError:
error_handler_or_other_stuff()
My question is: in general, how "fast" try - except constructs are to handle exceptions? Is it OK to use it a lot, or it's still faster to do the stuff "manually". Also sometimes I have the situation where I have to convert value to integer:
try:
some_var = int(dict.pop("something"))
except KeyError:
error_handler_or_other_stuff("no such key")
except ValueError:
error_handler_or_other_stuff("bad value for key")
Now the solution with exceptions seems to be quite nice, since I can do both of the checks in one step, also I removed the original key/value pair from dict, which is part of the problem. So I can tell at least: it looks like an elegant solution. However I am not sure it's faster or if it has other disadvantages I should worry about.