News for hackers. Stuff that matters.
Re:Checked exceptions: Java’s biggest mistake (2014) by chriswarbo on Friday September 11, 2020 @11:11AM (#24443659)
I've been using Scala quite heavily recently, having mostly used Haskell for years, with distant memories of Java. Scala allows Java methods to be called, but doesn't bother with checked exceptions, which has bitten me quite a few times.

My preferred style of error-handling is Option/Either, since I can implement the 'happy path' in small, pure pieces; plug them together with 'flatMap', etc.; then do error handling at the top with a 'fold' or 'match'.

Exceptions break this approach; but it's easy to wrap problematic calls in 'Try' (where 'Try[T]' is equivalent to 'Either[Throwable, T]').

The problem is that Scala doesn't tell me when this is needed; it has to be gleaned from the documentation, reading the library source (if available), etc.

I get that a RuntimeException could happen at any point; but to me the benefit of checked exceptions isn't to say "here's what you need to recover from", it's to say "these are very real possibilities you need to be aware of". In other words checked exceptions have the spirit of 'Either[Err, T]', but lack the polymorphism needed to make useful, generic plumbing. The article actually points this out, complaining that checked exceptions have to be handled/declared through 'all intervening code'; the same can actually be said of 'Option', or 'Either', or 'Try', etc., but the difference is that their 'intervening code' is usually calculated by the higher-order functions provided by Functor, Applicative, Monad, Traverse, etc.

It's similar to many developer's first experience of Option/Maybe: manually unwrapping them, processing the contents, wrapping up the result, then doing the same for the next step, and so on. It takes a while to grok that we can just map/flatMap each of our steps on to the last (or use 'for/yield', do-notation, etc. if available). It would be nice to have a similar degree of polymorphism for checked exceptions. Until then, I'd still rather have them checked (so I can convert them to a 'Try'), rather than getting no assistance from the compiler at all!

Re:Checked exceptions: Java’s biggest mistake (2014) by mlk on Friday September 11, 2020 @12:28PM (#24444436)
I absolutely agree, a checked exception is pretty much a Either<Exception, RESULT>, it only has a different (arguably ugly) syntax, I don't get all the hate. A "sufficiently intelligent compiler" could have turned signature with throws declarations in signature returning Either<Exception, T> but the hivemind has spoken and checked exception were simply ignored (see Scala and Kotlin)
Re:Checked exceptions: Java’s biggest mistake (2014) by ragnese on Friday September 11, 2020 @12:47PM (#24444609)
Kotlin made the worst mistake here. At least Scala actually gives you ways to do error handling somewhat ergonomically with for comprehensions. Kotlin gives us nothing. Sure, you're "supposed" to return sealed classes and match on them. But it's so tedious and non-obvious that I've literally never seen it done in any Kotlin code I've depended on.
Re:Checked exceptions: Java’s biggest mistake (2014) by benjiweber on Friday September 11, 2020 @04:14PM (#24446865)
They're so similar you can easily translate between the two e.g. https://github.com/unruly/control/blob/master/src/test/java/...
Re:Checked exceptions: Java’s biggest mistake (2014) by kevmo314 on Friday September 11, 2020 @11:16AM (#24443709)
The compiler can still help without needing to resort to checked exceptions. For example, `Either[T, Either[FileNotFoundCheckedException, RuntimeException]]` is basically isomorphic to a function that returns T or throws and has the same monad support, but can still force the developer to handle the checked exceptions.

I'm not sure if it really addresses the underlying concern that the article presents though, which seems more like checked exceptions seem to be used in a way where the developer has no recourse anyways, so surfacing it through a monad or checked exception doesn't matter.

Re:Checked exceptions: Java’s biggest mistake (2014) by chriswarbo on Friday September 11, 2020 @01:21PM (#24445037)
> For example, `Either[T, Either[FileNotFoundCheckedException, RuntimeException]]` is basically isomorphic to a function that returns T or throws and has the same monad support, but can still force the developer to handle the checked exceptions.

Yes, and I tend to write my code this way (although I find right-biased 'Either' a bit cleaner). The problem is (a) the mountain of JVM code which uses checked exceptions instead plus (b) the Scala compiler completely ignoring that exception information. Solving (a) is unrealistic, but (b) is an entirely self-imposed decision by the Scala developers. Their type checker could have incorporated checked exceptions in exactly the way you describe, and I wouldn't have any complaints (about exceptions, at least... null is a whole different beast ;) )

Re:Checked exceptions: Java’s biggest mistake (2014) by Atomskun on Friday September 11, 2020 @11:34AM (#24443900)
What's the difference to modeling the "happy path" with function calls one after another, with an outermost try block that can catch any exception that might have happened inbetween?

These functions wouldn't even need to care about Some[T]; T is enough.

Re:Checked exceptions: Java’s biggest mistake (2014) by chriswarbo on Monday September 14, 2020 @01:21PM (#24472652)
There are three possibilities:

                         | Polymorphic exceptions | Monomorphic exceptions
    ---------------------+------------------------+------------------------
      Checked exceptions | Unsupported            | Java
    ---------------------+-------------------------------------------------
    Unchecked exceptions |                      Scala
If exceptions are unchecked then there is no difference between "inner" code and "outermost" code; the compiler cannot tell us that a handler is needed/missing. This is the case in Scala. The advantage is that we can compose code which throws and which doesn't throw (this is essentially dynamic typing for exceptions).

If exceptions are checked then there is a difference between "inner" code and "outermost" code: the inner code has 'throws Foo' annotations, the "outermost" code doesn't. The compiler will spot missing handlers (i.e. when our outermost code can throw). There are two ways this could be done:

If checked exceptions aren't polymorphic then we need to make multiple versions of higher-order functions, like List::map: one version which doesn't throw, one which can throw one exception, one which can throw two exceptions, etc. (these exceptions can be kept generic, but the number of them must be explicit). For example if we have a lambda which can throw KeyNotFound we can't use it with the standard List::map method, since that only accepts lambdas which don't throw. We could make an alternative method 'public List<B> mapE(FunctionE<A, B, E> f) throws E', but that wouldn't work for lambdas which can throw FileNotFound and PermissionDenied; we could write a 'public List<B> mapEE(FunctionEE<A, B, E1, E2> f) throws E1, E2', but that wouldn't work for three exceptions, and so on. AFAIK this is the current situation in Java.

If checked exceptions could be polymorphic, similar to row polymorphism ( https://en.wikipedia.org/wiki/Row_polymorphism ) or algebraic effect systems ( http://lambda-the-ultimate.org/taxonomy/term/35 ), then we would have the best of both worlds. In this setup the 'E' in an annotation like 'throws E' doesn't stand for a name, but for a set of names. Higher-order functions like 'map' can throw the same set of exceptions as the lambda they're given, and that set could have any size: if the lambda can't throw any exceptions then map's set of exceptions is empty; if it can throw five types of exception then map's set of exceptions contains those five; and so on. This is becomes even clearer for things like function composition:

    public Function<A, C> compose(Function<B, C> f, Function<A, B> g)
If 'f' can throw something from set E1 and 'g' can throw something from set E2, then 'compose(f, g)' can throw something from set E1∪E2. Likewise if something can throw E1 and we have handlers for E2, then the result can throw E1 \ E2.

AFAIK the JVM can't do this, nor can those languages which typically target it (Java, Scala, Kotlin, etc.; Idris has algebraic effects and it can run on the JVM, although it's not the standard target)

Re:Checked exceptions: Java’s biggest mistake (2014) by shawnz on Wednesday September 16, 2020 @02:03PM (#24495383)
How aren't Java exceptions already polymorphic? "catch (Exception e)" will also match subclasses of Exception, won't it? And in the composition example, the compiler would correctly see that f(g(...)) can throw any subclass of E1 or E2. The only problem admittedly is that there's poor support for checked exceptions when used with lambdas, but isn't that just a language problem and not a JVM issue?

Although it's not possible to infer the exceptions automatically you can write a function to compose functions with exceptions and it will be checked at compilation time like you'd expect: https://gist.github.com/shawnz/5e9a0d344a6a693b46c662c5c8124... (EDIT: Actually they can be inferred to some extent.. example updated)

NVM. I see you addressed the possibility of doing this already.

Re:Checked exceptions: Java’s biggest mistake (2014) by chriswarbo on Wednesday September 23, 2020 @04:54AM (#24564648)
There are two ways we can make exceptions polymorphic:

- Subtype polymorphism lets us say things like 'throws Exception', 'catch (Exception e) {...}', etc. and this will work for any sub-class of Exception, e.g. 'FileNotFound'. This works by upcasting: essentially discarding some of the information about the type, so the intermediate code can rely on a smaller interface. If we try to downcast it later, we need to handle the possibility that it doesn't match; e.g. we can write 'catch (FileNotFound e) {...}', but that won't remove the 'throws Exception' annotation, since we haven't handled the other possibilities.

- Parametric polymorphism (AKA generics) lets us say things like 'throws E', where E can be instantiated to any specific class, e.g. 'FileNotFound'. This doesn't upcast: the full type information is propagated (but the generic steps aren't allowed to use it). We don't need to downcast: the type checker will instantiate the generic types to that specified by the source, and see if the destination type matches. If 'E' is instantiated to 'FileNotFound', and we write 'catch (FileNotFound e) {...}', then the annotation will be removed, since there's nothing else to handle.

Hopefully the problem with the generic approach is clear from your example: we have to re-implement things over and over for different numbers of exceptions ('FuncThrowingOneException', 'FuncThrowingTwoExceptions', etc.)

Thinking about it, the situation is similar to Haskell's "constraint kinds": Haskell can "constrain" types (i.e. require interfaces), e.g.

    showBoth :: (Show a, Show b) => a -> b -> String
    showBoth x y = show x ++ ", " ++ show y
This is roughly equivalent to the Java:

    String showBoth<A extends Show, B extends Show>(A x, B y) {
      return x.show() + ", " + y.show();
    }
The GHC compiler has an extension "constraint kinds", where the constraints are treated more like normal values (similar to exceptions). The interesting part for this scenario is that each constraint is treated as a single value, so something like "(Show a, Show b)" is a single (tuple) value. Yet the type checker is smart enough to look inside such tuples, e.g. it knows that "(Show a, Show b)" implies "Show a", etc. It also doesn't care about order, e.g. "(Show b, Show a)" will work just as well; or nesting, e.g. if "c1" is "(Foo a, Bar a)" and "c2" is "(Bar a, Baz c)" then "(c1, c2)" is equivalent to "(Foo a, Bar a, Baz c)".

Those are the sort of features that would make generic exceptions much nicer, since we could put 'throws E' on everything, and be able to instantiate E to a single exception (like "FooException"), or a tuple of multiple exceptions (e.g. "(FooException, BarException, BazException)"), or a tuple of no exceptions "()". There's probably a way to encode this already, but it would require manually packing, re-arranging and unpacking the exceptions at every use-site.

Re:Checked exceptions: Java’s biggest mistake (2014) by barrkel on Friday September 11, 2020 @11:21AM (#24443769)
The right way isn't Either / Option (though it's a lot more viable with top-level type inference); it's unchecked exceptions.

Checked exceptions have bimodal usage, from the programmer POV. Either you care about the exception, and you deal with it very close to the throw point, or you don't care about the exception, and it should be handled far far away, across many stack frames.

The former isn't a problem. It's the right thing if e.g. you try to open a file and the file is missing, and you have reasonable error handling logic to retry, open a different file, replace the file and try again, whatever.

The latter is where the issue lies. If you're handling errors far away, then you're handling lots of different errors there, and you're not distinguishing between them, because there's too many different failure modes. You're most likely just in a loop logging errors, or terminating. You're too far from the cause of the exception to do anything specific with it, the context is lost. So the effort to transport the exception type throughout the call graph is pointless.

tl;dr: checked exceptions are fine near the leaf of the call graph, but are increasingly pointless towards the trunk.

Re:Checked exceptions: Java’s biggest mistake (2014) by hota_mazi on Friday September 11, 2020 @03:00PM (#24446171)
Unchecked exceptions are the worst of both worlds: you can call a function that will throw an exception that you could recover from but you have no idea, so you don't even know you should catch it.

At least, Either/Option force your code to take errors into account.

You still have to bubble them up and compose them manually, though, which is why checked exceptions shine.

Re:Checked exceptions: Java’s biggest mistake (2014) by xienze on Friday September 11, 2020 @11:38AM (#24443928)
> You're too far from the cause of the exception to do anything specific with it, the context is lost.

Which is perfectly fine. If you _can_ handle the exception near where it happened, do so. Otherwise bubble it up and log it or whatever.

Consider a REST service. If a DB or other error happens, I can retry right then and there if business logic calls for it (probably not), or just kick the can down the road where something appropriate like a 500 response serializer will take care of it. That’s a great pattern in my opinion.

Re:Checked exceptions: Java’s biggest mistake (2014) by chriswarbo on Friday September 11, 2020 @01:14PM (#24444949)
> If you're handling errors far away... the context is lost. So the effort to transport the exception type throughout the call graph is pointless.

I get what you're saying, and things like 'Try[T]' lose the specifics of the error type too (we just get a 'Failure(Throwable)').

My problem occurs earlier on: which code might throw exceptions, and why? Java's checked exceptions let methods declare "I can fail with an AccessDenied error (along with all the usual stuff like NullPointerException, etc.)", and the compiler will make sure that's handled somewhere (even if it's just a log and quit).

Unchecked exceptions are implicit; the signatures don't tell us they exist, and the compiler doesn't check that they're handled. This makes sense as a last resort, for things like OutOfMemory (although Zig would disagree!); but in general it's unhelpful and dangerous. I think it's a poor choice on Scala's behalf to treat all exceptions this way. Their only redeeming feature is short-term convenience; it's essentially an instance of static versus dynamic typing. "Exception polymorphism" (which I imagine would look something like row polymorphism) would make checked exceptions more convenient, since we wouldn't need exception-specific boilerplate, and this might be enough to solve the problem.

Maybe the JVM might gain such a feature in the future, but until then we can use 'Either' or 'Try' to achieve a similar thing: they show us explicitly which methods can fail (answering the question in my second paragraph), and they force us (via the type checker) to handle the error case somewhere (even if that's just a generic log+quit handler at the top level, as you say).

Re:Checked exceptions: Java’s biggest mistake (2014) by ragnese on Friday September 11, 2020 @12:49PM (#24444641)
So you're saying checked exceptions are perfectly fine.

I'll write my library code with checked exceptions. You call my library code in one of your methods. The compiler tells you to do something about the possible failure. If you want to handle it there, you handle it with a try{}catch{}. If you don't, you wrap it in a RuntimeException and rethrow it so your top level handler can deal with it.

Perfect.

Unchecked exceptions make it easy to fuck up the case where you actually might want to handle it close to the call.

Re:Checked exceptions: Java’s biggest mistake (2014) by dpc_pw on Friday September 11, 2020 @02:03PM (#24445517)
`Result<T, dyn Error>` from Rust (since I'm not a Haskeler) is a result that can contain any error. Which is exactly what unchecked exceptions are.

Rust developers can fluently switch and convert between conrete `Result<T, SomeErrorEnumeration>` and `Result<T, dyn Error>`. It works beautifully. Libraries usually enumerate their errors (leafs), applications usually just throw everything to one universal error bag.

Re:Checked exceptions: Java’s biggest mistake (2014) by chriswarbo on Monday September 14, 2020 @01:39PM (#24472851)
> Rust developers can fluently switch and convert between conrete `Result<T, SomeErrorEnumeration>` and `Result<T, dyn Error>`

That's something different, since both cases tell you that errors might occur.

In Java we can do the following:

    public int concreteChecked() throws FileNotFound {
      if (bar) throw new FileNotFound();
      return 42;
    }

    public int polymorphicChecked() throws Exception {
      if (bar) throw new FileNotFound();
      return 42;
    }

    public Either<FileNotFound, int> concreteEither() {
      return bar? new Left(new FileNotFound()) : new Right(42);
    }

    public Either<Exception, int> polymorphicEither() {
      return bar? new Left(new FileNotFound()) : new Right(42);
    }

    public int unchecked() {
      if (bar) throw new RuntimeException(new FileNotFound());
      return 42;
    }
I think your 'Result' examples are like the third and fourth examples above: using a sum type, differing by whether the error is more/less specific.

The first and second use checked exceptions, again differing in whether the error is more/less specific. Importantly: these will refuse to compile if we don't have 'throws ...' in their signature.

The last example uses an unchecked exception: if we throw 'RuntimeException' (or a subclass), we don't need to put 'throws ...' in the signature, and hence the compiler won't keep tell us to put 'catch' block anywhere.

Re:Checked exceptions: Java’s biggest mistake (2014) by dpc_pw on Tuesday September 15, 2020 @01:02PM (#24483593)
In Rust you can do `Result<T, dyn SomeErrorInterface>` as well, which makes it able to express everything exactly like Java can. It's just Rust community generally doesn't bother with the taxonomies of errors. You either get a concrete list, or "any error".
Re:Checked exceptions: Java’s biggest mistake (2014) by overraskning on Friday September 11, 2020 @11:44AM (#24443997)
I think you're making a good point here if you look at it as an application developer. In my experience, checked exceptions are helpful when using a library. Would you recommend this approach for libraries as well or do checked exceptions have more of a role to play there?