logoalt Hacker News

voidfuncyesterday at 2:22 PM3 repliesview on HN

Checked exceptions are controversial mostly because a lot of the core APIs use them in places where it's pointless to check, like IOException.

Using them correctly can be great tho.


Replies

dmuxyesterday at 3:15 PM

>in places where it's pointless to check, like IOException

Can you explain why this is pointless? In my mind, this being a checked exception would hopefully be a hint that I should think about this failure-case and make an explicit decision whether to handle it or not. Network connection failed? Maybe I retry. Maybe I store that data somewhere else as a fall back. Isn't this similar to Go programmers needing to check if err is not nil?

show 1 reply
PaulHouleyesterday at 2:40 PM

Mostly I think they are a mistake, like in ordinary application code instead of catching close to the throw you want to do a lot of

  try {
     ...
  } finally() {
     ...
  }
to make sure things get torn down that have to be torn down and let the exception go to the top of the unit of work and probably to whatever drives the work unit. You can probably do better than logging the raw exception and moving on to the next work unit but you can do much worse. That is, you want a default "sloppy" error handling approach that's correct that you can do without thinking and avoid other kinds of "sloppy" coding encouraged by checked exception such as catching exceptions locally without doing the right thing globally.

Occasionally though I have built something really sensitive, like an authentication filter for a web site which has at least 5 ways to log in and in that I have a hierarchy of exceptions and use checked exceptions heavily to document all the ways things can go wrong and felt like "the type system really has my back here" but that is like 5% of the Java I write.

show 1 reply
ndriscollyesterday at 2:49 PM

Scala's ZIO also demonstrates that they're a great idea and can be perfectly ergonomic, but you need type inference, which Java devs were resistant to for a long time (maybe still are? I remember lots of "how will I ever know what `val a = new Animal()` is???"). If you infer the exception type, they're basically invisible except for when you forget to have some place in your program to handle them, which is exactly what you want.