Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is exception handling always expensive?

I've been told time and again that exception handling for operations like determining type is bad form since exceptions are always computationally expensive. Nevertheless, I've seen posts (especially Python-related ones, such as the to reply of this one) that advise using exception handling for exactly that purpose.

I was wondering, then, if throwing and catching exceptions is to be avoided universally, because it is always computationally expensive, or whether some languages, such as Python, handle exceptions better and it is permissible to use exception handling more liberally.

like image 363
user1576628 Avatar asked Jan 11 '23 06:01

user1576628


1 Answers

You cannot give general advice such as "exceptions are expensive and therefore they should be avoided" for all programming languages.

As you suspected, in Python, Exceptions are used more liberally than in other languages such as C++. Instead of raw performance, Python puts emphasis on code readability. There is an idiom "It's easier to ask for forgiveness than for permission", meaning: It's easier to just attempt what you want to achieve and catch an exception than check for compatibility first.

Forgiveness:

try:
    do_something_with(dict["key"])
except (KeyError, TypeError):
    # Oh well, there is no "key" in dict, or it has the wrong type

Permission:

if hasattr(dict, "__getitem__") and "key" in dict:
    do_something_with(dict["key"])
else:
    # Oh well

Actually, in Python, iteration with for loops is implemented with exceptions under the hood: The iterable raises a StopIteration exception when the end is reached. So even if you try to avoid exceptions, you will use them anyway all the time.

like image 200
Ferdinand Beyer Avatar answered Jan 17 '23 17:01

Ferdinand Beyer