Skip to content

Comment on Stop Catching Exceptionsparent

Comments

If you get an error, but the error is within a closed subset of your program, you should not propagate the error upwards. Let's say you are sending data to another program on the same system. The other program could do many things, and could send answers you do know how to reply to. The error is in your function and in your function alone - you should simply exit the function without exiting the program. The range of errors are limited, and none of them are life threatening, but only your function knows that, the rest of the program is unaware of what the unknown error means.

Propagating errors upwards like you say breaks functionality encapsulation.

What you said does not contradict my statement: only catch errors you know how to handle. You presented a situation in which you did know how to handle the error.

But if you don't know how to handle it, you should still throw it up, even if it breaks functionality encapsulation. This will likely crash the application, but the source of the error will be easily traceable, and the underlying problem can be fixed.

Can you give some examples of errors that should be thrown upwards? What percentage of errors in a program belong to this group?

The most obvious to me is when you know something should be one of a finite set of values, and its actual value is not in that set. In my compiler, I have to classify array accesses as either a row or a column access. After a certain point, if it's neither (unitialized), then it's a serious error, I can't continue, and I throw an exception. I have similar situations when I deduce the types of an expression. Since I perform transformations on code, I also expect to find certain variables at certain places - if I can't find it anywhere, then I throw an exception.

Some of these are exceptions that I can recover from in that while the compilation is broken, I can still continue to find more errors. Others are show stoppers. I encounter these kinds of errors every time I have to do any decision based on these properties, which is often.

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.