logoalt Hacker News

edflsafoiewqyesterday at 11:09 PM4 repliesview on HN

Python's

    f = open('foo.txt', 'w')
is even more succinct, and the exception thrown on failure will not only contain the reason, but the filename and the whole backtrace to the line where the error occurred.

Replies

9rxtoday at 12:15 AM

But no context, so in the real world you need to write:

    try:
        f = open('foo.txt', 'w')
    except Exception as e:
        raise NecessaryContext("important information") from e
Else your callers are in for a nightmare of a time trying to figure out why an exception was thrown and what to do with it. Worse, you risk leaking implementation details that the caller comes to depend on which will also make your own life miserable in the future.
show 1 reply
verdvermyesterday at 11:36 PM

We were taught not to use exceptions for control flow, and reading a file which does not exist is a pretty normal thing to handle in code flow, rather than exceptions.

That simple example in Python is missing all the other stuff you have to put around it. Go would have another error check, but I get to decide, at that point in the execution, how I want to handle it in this context

show 1 reply
Mawrtoday at 3:38 AM

And also nothing about that code tells you it can throw such an exception. How exciting! Just what I want the reason for getting woken up at 3am due to prod outage to be.

oncallthrowyesterday at 11:24 PM

> the exception thrown on failure will not only contain the reason, but the filename and the whole backtrace to the line where the error occurred.

... with no other context whatsoever, so you can't glean any information about the call stack that led to the exception.

Exceptions are really a whole different kettle of fish (and in my opinion are just strictly worse than even the worst errors-as-values implementations).

show 1 reply