Hacker News new | ask | show | jobs
by ghc 4669 days ago
Certainly not. In Python, for example, exceptions are used to handle exceptional conditions.

Here's an example. Say I'm writing a function and I have a dictionary I need to access values from often. Now say that 85% of the time the key I need is in the dictionary, but 15% of the time it is not. I could do this:

    if key in my_dict:
        execute_operation(my_dict[key])
    else:
        pass
So that if the key is not in the dictionary I do nothing. But this can be expressed more clearly like this:

    try:
        execute_operation(my_dict[key])
    except KeyError:
        pass
This is considered to be clearer because it expresses the fact that the key should be in the dictionary, but in some cases is not. And interestingly, performance reflects this. The first method is more efficient in cases where the key is usually not in the dictionary. The second method, on the other hand, is more efficient when the key is usually present in the dictionary.

So, in summary, exceptions are used in Python to represent cases where successfully executing the code within the try block is normal, but exceptional conditions could once in awhile occur. Almost all uses of exceptions occur for conditions where the program should not crash. When the program should crash we just let the exception bubble up to the top level where we gracefully shut down the program and call an exit function.

3 comments

Unfortunately, the second one eats an uncaught KeyError raised deep inside execute_operation, not just my_dict[key] failing. Which may be easy to overcome if you wrote all the code and libraries that execute_operation calls, but nearly impossible otherwise.
As a C programer i consider the first method to be clearer and am still unconvinced that exceptions should be user for anything other than unrecoverable errors; exceptions have the stack unwinding feature.
Python also has a `StopIterationError` that is raised to signal the end of a `for` loop, which is not exceptional at all.
It's called "StopIteration", not "StopIterationError", because it is not an error.