You also have a problem similar to "monads and logging": if you want to log from anywhere in your program, your logging function needs to be exception-tight and deal with all the possible problems such as running out of disk space, otherwise you have to add those everywhere.
The worst part about them is that for some reason even standard library methods will throw them. Like when you try `list.Add(1)` on a list without checking if said list is read-only. The overhead of having to read every single bit of documentation in the standard library just to be ahead of panicking standard methods is infuriating.
That's got nothing to do with the concept of checked/unchecked exceptions, though, that's just Java's mediocre standard library.
I started working in Java a few months ago and holy shit does this stick out like a sore thumb. Null checks cascade down from gods domain all the way to hell. But oop we missed one here and caused an outage lol add one more! So much wasted human effort around NPE, and yet, we sit around in a weekly meeting getting yelled at about how stability needs to be taken more seriously. Hrm.
If you build an entire program with nullability checking on it's pretty great, though.
Reality does indeed feel exactly like what you mentioned with C#, though. The annotation is going to be missing where it’s needed most unless something forces the whole project to use it.
Even better, apply at the package level via `package-info.java` (unfortunately sub-packages need to be individually marked as well)
@NullMarked
package com.foo;
import org.jspecify.annotations.NullMarked;Recoverable errors should all be checked exceptions, and a part of each function's type signature. This would still be a huge pain to deal with, though, with the existing syntax.
Additionally, the way result types work, isn't much different, from type system theory point of view.
I really miss them in .NET projects, because no one reads method documentation, or bothers to have catch all clauses, and then little fellow crashes in production.
IoC, DI, aspects, annotations, ORMs, whatever Spring is, runtime code generation, etc.
The rationale is something like "runtime metaprogramming would be really terrific, were it not for all those pesky checked exceptions".
This is precisely why they are so bad: checked exceptions must not be allowed to be used outside the package (or jar, or whatever, just limit it) otherwise they cause non-local build failures in all dependencies. They're fine if you are developing the artifact that's going to be deployed.
It would be equally problematic to change the method name, or the argument arity or types (ignoring overloading for the moment).
It would be even more problematic if I kept the same function signature, but changed the meaning of the parameters. Then your breakage is silent.
It sounds ok from a library authors perspective but definitely not from a library consumer perspective.
A sane thing to do would be to do a version bump.
2. The difference between altering your un/checked exceptions is not whether consumers will have to react, but how it shows up and how badly you will ruin their day. A checked exception is unambiguously better. It will immediately break their build at the same time they ought to be expecting build-breaks, and the compiler will give them a clear and comprehensive list of cases to address. In contrast, an unchecked exception may let them compile but it will break their business in production, unpredictably.
Re 2) that's what it must've sounded like in theory in the conference room when they were designing that part of the language. In practice, the upgrade of the library will never happen if it breaks the build. Production should catch all runtime exceptions and be able to restart itself gracefully anyway because cosmic rays don't make sense as checked exceptions.
Look, I get it: Sometimes a Checked Exception defined in a niche spot "infects" higher-level code which adds it to their signatures, because nobody takes the time to convert it into something more layer-appropriate.
But that is the exact same kind of problem you'd also get when library's NicheCalculationResult class is trickling upwards without conversion too! However nobody freaks out over that one. Not because it's mechanically different, but because it's familiar.
absolutely, but the catch is it doesn't affect me transitively. the immediate caller must deal with the issue somehow. with exceptions, this it is expected to not handle the ones you have no business handling, so you should change your signature. this propagates upwards and there is no layer of abstraction that can handle this problem without breaking the world. the only somewhat sane way is wrapping the new exception is something that you already handle - if that makes logical sense, which it very well might not.
> NicheCalculationResult class is trickling upwards
yes, and yes people do freak out, not sure why you think they aren't :)
Actually sounded great right up until this point. Deal with it, or explicitly acknowledge that you do not. It's honest.
Apparently other developers are why we can't have nice things.
So what's left in exception handling is logging and/or rethrowing. And the 'nasty hackish way' of doing it (RuntimeException) already passes a complete stack trace up to the caller.
Lots of different kinds of software tends to follow this pattern - web servers, data pipelines, compilers/build tools, etc.
I think IOException (or maybe FileSystemException) is probably the best you can do in a lot of I/O cases unless you can dedicate time to handling each of those specially (and there's often not a lot much more you can do except for saying "Access is denied" or "File not found" to the user or by logging it somewhere).
But most IO errors are fatal. It doesn't matter if the filename is not found, or the controller had too many errors talking to the drive and gave up - either way your code can do nothing.
edit, so like `@throws[T <: Exception] def effect[T](): Unit` or something, how is it supposed to work?
<R> List<R> map(Function<? super T,? extends R> mapper) { ... }
<R, E1 extends Throwable> List<R> map(FunctionThrows1<? super T,? extends R, E1> mapper) throws E1 { ... }
<R, E1 extends Throwable, E2 extends Throwable> List<R> map(FunctionThrows2<? super T,? extends R, E1, E2> mapper) throws E1, E2 { ... }
and so on until you get bored.(Except that then you have to decide what your generic function is going to do if the callback throws an exception...)
> (Except that then you have to decide what your generic function is going to do if the callback throws an exception...)
Exactly. Presumably you don't want to handle them and want to throw them up to the caller. But now your function has to be "throws Throwable" rather than throwing the specific exception types that the callback throws.
Of course in general the manual effort to do that in a large code base ends up too hard and so in the real world nobody does that. Still the ideal is good, just the implementation is flawed.
I haven't done java in decades, but I imagine this would get really nasty if you are passing a callback to a third party library and now your callback throws the new exception.
Checked exceptions seem like a great idea, but what java did is wrong. I'm not sure if other implementations are better.
You have no way to assert that the error is always correctly handled in the codebase. You are basically crossing your fingers and hoping that over the life of the codebase you don't break the invariant.
What was missing was a good way to convert checked exceptions from code you don't own into your own error domain. So instead java devs just avoided them because it was more work to do the proper error domain modeling.
It gets worse. Sometimes we can prove that the 21st function because of the way it is calling your function can never trigger that exception, but still it will need code to handle it. If that handler code if the 21st function changes to trigger the exception now should be propagated back down but since you handled the exception before checked exceptions won't tell you that you handled it in the wrong place.
I don't know how to implement checked exceptions right. On paper they have a lot of great arguments for them. However in practice they don't work well in large projects (at least for java)
You could imagine something similar with Exceptions where there is simple and ergonomic way to rethrow the exception into your own error domain with little to no extra work on the part of the developer.
One should be cautious every time it feels like there is an obviously right way to do something that everybody fails to see :)
What? No you don't. You can just propagate up the errors you can't handle with the types they come with.
If I understand properly what you are suggesting, to make it work with my goto language (OCaml), I believe that I would have to make every function return a polymorphic variant for the error (aka technicaly equivalent to mandatory try blocks and boxed return types). The only time I had to deal with a library doing that it was not pleasant but it was too long ago for me to remember the details, probably related to complex compilation error messages.
(*) looking at your github, I guess Scala?
Today I write C# at my job and I could not be happier with the usage of exceptions.
> Exceptions and panics can still creep so it's not even "safer"
This part is just as true for checked exceptions - you still have unchecked exceptions too. Ultimately you can't get away from needing a way to bail out from unrecoverable states. But "secondary state that is recoverable and understandable, but should be handled off the primary codepath" is a very useful tool to have in your vocabulary.
> Today I write C# at my job and I could not be happier with the usage of exceptions.
How do you do e.g. input validation? Things that are going to be 4xx errors not 5xx errors, in HTTP terms. Do you use exceptions for those? (I note that C# doesn't have checked exceptions at all, so there's no direct equivalent)
That's why I'm against checked exceptions in general: I avoid them in Java as much as possible.
> "All functions end up returnig `Either/Result`" is a sign you're doing something wrong.
I agree, that's why I'm sharing that it's a bad idea. I've had this experience recently in a team of very experienced developers (some of them who even have books written). In the wild you have Go in which essentially all non-trivial functions return `X, error`.
> How do you do e.g. input validation? Things that are going to be 4xx errors not 5xx errors, in HTTP terms
Recently I've been working on a piece of code that deals exactly with that. For such use cases we use the `bool Try(out var X)` pattern which follows what you have in the standard library (see `int.TryParse(string input, out int result)`) which works but I'm not a fan of. For this use case a `Either/Result` would work great, but is a very localized piece of code, not something that you would expect to see everywhere. Also, you might want to roll (or use) a specialized `Validation` type that does not short-circuit when possible (ex. in a form you want to check as many fields as possible in a single pass).
In summary, I'm not against the existence of `Either/Result` in general, I think there are great use cases for them (like validation); what I'm against is the usage of them to signal all possible type of errors, in particular when IO is involved.
I agree that a checked error type is a bad way to represent IO errors that most programs won't want to handle (or will handle in a very basic "retry the whole thing at high level" way). I think a lot of functional IO runtimes are converging on a design where IO actions implicitly carry some possibility of error that you don't have to nest in a separate either/result type.
Syntactic sugar it needs is an easy way (like ! prefix) to turn it to a runtime exception.
Procrastinating on exceptions is usually the correct thing to do in your typical business application - crash the current business transaction, log the error, return error response. Not much else to do.
Instead the applications are now littered with layers of try-catch-rethrow (optionally with redundant logging and wrapping into other useless exceptions) which add no benefit.
status = DoThing(); if(status != allIsWell) {return status;}
C++ embedded for a long time has said don't use exceptions they are slow. However recent thinking has changed - turns out in trivial code exceptions are slow but in more real world code exceptions are faster than all those layers if checks - and better yet you won't give up on writing all the if checks. Thus embedded projects are starting turn exceptions on (often optimized exceptions with static pre allocated buffers)
The final "print something when wrong" is of little value, but the unwinding is very valuable.
For some reason some Go programmers think those lines are the best thing since sliced bread.
This is not, of course, the only way that checked exceptions can be utilized. But, all too often, that is by far the easiest way to reason on them. They represent a decision that needs to be bubbled up to the operator of the overall system.
Worse, the easy way to explain how the system should resume, is to go back to where the exception happened and to restart with some change in place. Disk was full, continue, but write to a new location. That is, having the entire stack unrolled means you wind up wanting the entire process reentrant. But that is an actively hostile way to work for most workflows. Imagine if, on finding a road was closed, a cab driver took you back to pick up location to ask what you want to do about it.
If it is not something that you want to unwind the stack, or bubble up to the users, then you go through effort to wrap it so that it is another value that is being processed.
I'm not saying exceptions are good, but I am saying that they do represent the most common error handling pattern.
My assertion is that actual error handling in workflows doesn't work in that manner. Automated workflows have to either be able to work with the value where it was broken, or generally just mark the entire workflow as busted. In that scenario, you don't bubble up the exception, you instead bubble up an error code stating why it failed so that that can be recorded for later consideration. Along the way of bubbling up, you may take alternative actions.
I also find that generally exceptions can't be meaningfully caught until much higher in the call-stack. In which case, a lot of intermediary methods need to be annotated with a checked exception even though it's not something that matters to that particular method. For this reason, I've really come around on the Erlang way of doing things: throwing runtime exceptions in truly exceptional situations and designing top level code so that processes can simply fail then restart if necessary.
Some of these things are mildly annoying when you think about them in theoretical terms.
But all the professional teams I've been on a (a lot) have successfully dealt with exceptions without issue. The teams settled on an exception and error handling process early in the design phase and it rarely has caused a major issue.
Yet it seems out on the internet in any place where programming languages are discussed it is an insurmountable problem that has caused all projects in Java to fail and the language died an early and unpopular death. It seems if it caused anyone huge problems it was not Java's issue but that team's issue.
There are/were other much bigger issues over the years. Memory leaks have been issues. Spring was hard for many people to deal with back around 2005 or so. The first iterations were quite bad with XML. XML in general caused a lot of issues. J2EE caused a lot of issues just because it was so badly designed early on. (Some of this was because it was birthed out of CORBA, which was itself pretty horrible.) Plenty of issues were caused by using Collections with mixed objects in them early on before Generics were introduced. Visual J++ caused havoc. Different models of web application caused a lot of havoc before we got to Javascript UIs in the browser driven by Web API back ends. JPA was a big mistake IMO. But exceptions were never really a huge problem anywhere.
So many have blamed a problem on Java when it was actually a problem with a library, component, or framework written in Java that became way more popular than it should have been. And along the way there were a lot of "developer influencer celebrities" who were listened too far far more than they should have been. Many of these guys (I can't remember one ever being a woman) sold everyone on ultra complex designs and ways of doing things and the community almost always bought in to a ridiculous degree.
I work on an Inversion of Control system integration framework on top of a herd of business logic passing messages between systems. If I were to do all over again, then I’d have the business logic:
* return success or failure (invalid input)
* throw exception with expectation that it might work in the near future (timeout), with advice on how long to wait to retry, and how many retries before escalating
* throw exception with expectation that a person needs to check things out (authentication failure)
Unless the business logic catches it, unchecked exceptions are a failure. Discussion about what is what kind of exception is hard, but the business owners usually have strong opinions taking me off the hook.
This is less of a mind-was-changed case and more just controversial, but... Checked Exceptions were a fundamentally good idea. They just needed some syntactic sugar to help redirect certain developers into less self-destructive ways of procrastinating on proper error handling.
In brief for non-Java folks: Checked Exceptions are a subset of all Exceptions. To throw them, they must be part of the function's type signature. To call that function, the caller code must make some kind of decision about what to do when that Checked Exception arrives. [0] It's basically another return type for the method, married with the conventions and flow-control features of Exceptions.
[0] Ex: Let it bubble up unimpeded, adding it to your own function signature; catch it and wrap it in your own exception with a type more appropriate to the layer of abstraction; catch it and log it; catch it and ignore it... Alas, many caught it and wrapped it in a generic RuntimeException.