Hacker News new | ask | show | jobs
by ajnin 1720 days ago
> You don't want a program where in 100 different places you handle exceptions and pop up error dialogs. What if you want to change the way you put up that dialog box? That's just terrible. The exception handling should be centralized, and you should just protect yourself as the exceptions propagate out to the handler.

That's assuming a definition of an exception as a generic error you can do nothing about except tell it to the user and maybe retry the operation or kill the program. But in practice exceptions are used for more than that, they're a sort of union type where a method can return a result or an error, but because Java didn't have union types exceptions were used to signal that. For example parseInt will throw a NumberFormatException if it can't parse the string you pass as argument (NumberFormatException is unchecked but it really should be checked).

I think it's the coexistence of these 2 different ways things can go wrong under the same term that is the root of the confusion around Exceptions. The first way is using an exception as a normal outcome of a method, like parseInt above. Using the word "exception" for that is wrong, it is not exceptional for parseInt to return an error if you pass to it some string that does not contain a number. It is expected and will happen every time. The type system should be able to represent that with an union type or Either<> or something of the sort instead.

The second way things can go wrong is when the program is put in contact with the outside world, and the outside world is messy so things will happen that are not what you expect. You try to open a file but it cannot be found any more, you try to allocate some memory but the operating system refuses to do so, some network call is taking too long and so on. Those will have to be dealt with case by case, sometimes you can do something about it, sometimes not. I know programmers don't like that very much but I don't know what can be done about it, it's just the nature of dealing with all the edge cases.

1 comments

Exceptions are exactly the same thing as sum types, there really is no difference between them on a conceptual level. They just come with additional stack traces and good, no boilerplate syntactic sugar in Java.