by breadwinner · 3y ago · 0 comments
More on checked vs unchecked exceptions here: https://forum.dlang.org/thread/hxhjcchsulqejwxywfbn@forum.dl...
try {
theUpdatedFunction();
} catch (MyNewCheckedException e) {
logger.warn("Whoopsie doopsie", e)
throw new SomeUncheckedException("Something failed, idk", e)
}
Which really is a zero sum game. The code still breaks the same way, but the checked exception gets eventually wrapped in an unchecked one. We still would have the situation that someone changed the behavior of the function in a way that is incompatible with your usage.That bug should have been caught by tests, code reviews and good communication.
> You see programmers picking up new APIs that have all these throws clauses, and then you see how convoluted their code gets, and you realize the checked exceptions aren't helping them any.
And he goes on to elaborate on how this gets more complicated when versioning is introduced into the mix.
There's a reason we have compile-time checks. If you think compile-time checks should be replaced with additional tests, code reviews and good communication, then you want a scripting language, not a compiled language.
You do not wrap checked exceptions in an unchecked one... unless you are a really bad Java programmer.
Here's the thing. You've just described the vast majority of programmers - bad. They're really fucking bad. And language constructs that lead to bad programmers doing stupid things are, unfortunately making things worse for everyone.
Maybe a new testing paradigm will fix it, I certainly keep an eye out for them, but nothing so far. Property based testing is better, but mostly it just reminds me that we had Design By Contract 30 years ago.
I disagree -- this is the correct thing to do if you believe it is not possible for the checked exception to occur. (Catching it is wrong -- what would you do to correct something which you believe not to be possible? Forcing the caller to handle it is wrong -- if you don't know what to do with it, they sure won't!) Wrapping checked as unchecked encodes your belief that should it occur, it is a logic error, akin to out-of-bounds array access or null pointer dereference.
(Of course, swallowing expected exceptions one is simply too lazy to do anything about is poor practice! Not disagreeing with that.)
Actually no. For instance, the caller at some point up the stack may know if something is worth retrying.
If it is not possible to occur, then it should not be part of the API.
The only time I rethrow a checked exception as an unchecked exception is when the code is still under construction. The default of the eclipse code generator is to log and ignore caught transaction. I think wrapping into an unchecked one is the better default behavior for incomplete code under a "fail fast" policy.
I don’t think that’s close to sufficient to making checked exceptions work tho, let alone good.
Unfortunately, this ends up propagating out and your entire code base needs to also do this. Tho i reckon it will make your code better in the future, for a short term/temporary pain converting/adding breaking changes etc.
That's not a given. It's perfectly fine to handle a checked exception via some custom runtime. The nice part is your your code base was given a chance to handle the key exceptions of this particular api all from your ide without you having to refer to documentation etc.
Moreover, it's good that code nearest the site where the exception is thrown handles the error, as only it has context for what's going on at the time. Code further up the stack won't have any clue what this random IOException might relate to.
If you're confident the IOExceptions can't occur under normal conditions -- say, you know the file has correct permissions, isn't being concurrently modified, etc. -- then, encode this belief by catching the IOException near to its origin and rethrowing as an unchecked exception.
This same pattern shows up even in languages without exceptions. In C -- always check errno; don't try to catch SIGSEGV or SIGABRT; raise SIGABRT if errno is something you don't plan to handle. In F# -- you're forced to match Ok/Error; don't try to catch exceptions; raise an exception if you don't expect Error.
try {
theUpdatedFunction();
} catch (MyNewCheckedException e) {
logger.warn("Whoopsie doopsie", e);
throw new SomeUncheckedException(e.message);
}
There's a special place in Hell for these people, but at least they'll get to see all of their friends again. try {
somethingImportant();
} catch (Exception e) {
// can't happen
}
IJ finally started chirping about this other anti-pattern try {
doit();
} catch (Exception e) {
System.err.println("something didn't work");
// failure to reference "e" is now a yellowbox
}
I have to constantly ask for them to either log it, or rename the variable to `ignored` to get IJ and future readers on the same page that it was intentionally swallowedThat's not a valid argument. This is an explicit decision, so they reap what they sowed.
One could just as well make the same argument for Optionals, that you can just do:
let val = foo.unwrap();This is such an unproductive cop out response. The problem could be completely solved by functional error handling, which leverages the compiler to force you to handle exactly the errors than can happen, no more, no less.
Who does that? It looks like an anti-pattern.
I couldn't disagree more. Checked exceptions in Java have ruined a generation of programmers.
The truth is, under checked exceptions, to satisfy the compiler the function that you called would declare that it throws a SomeModuleException and the programmer who wrote that function would put all his code in try/catch block that catches all errors and rethrows a SomeModuleException with the real exception passed as the cause.
Checked exceptions just don't work.
I have seen libraries that make network calls that do the following:
* Throw an exception on certain types of network errors * Return an HTTP error code for other types of network errors * Return an object with error set to true and an error string for other types of network errors
NONE of those was documented, it is crazy. This actually bite me in prod when an undocumented exception that we hadn't seen in over a year of uptime was finally thrown. I had to look at network logs to try and figure out why it was being thrown (no checked exceptions in JS!), which itself is absurd.
This means it is impossible to add new exceptions to library methods without breakage, and even in your own code it may mean hundreds of changes throughout your code to add a new exception type.
Rusts solution seems to have improved this conundrum, where you can describe how to map the new error into an existing hierarchy in a single or a few places instead of at every call site
That’s a feature, not a bug. If it wouldn’t, an exception of that kind could bubble up at a place you didn’t expect.
Also, it doesn’t require that many changes, it only has to be changed up to the point where you intend handling it.
I don’t see how rust would be immune to that.
Though it is true that polymorphism with respect to checked exceptions would be great. The new generation of languages might have that (e.g. Koka)
That's a big problem with Java's checked exceptions, it's not very composable and flow control can just stack up into deeper and deeper "waterfalls" of code rather than simpler pattern matching. (To be fair that's a big problem with exceptions in general as "flow control", they aren't very composable.)
Something like an Either monad in a language with sum types can be a great way to describe errors/exceptions usefully as return types. From a type theory perspective, checked exceptions can be seen as a hack for a language that doesn't support sum types and doesn't have great native monad binding.
Exceptions can be thrown from anywhere. That's the documentation.
https://learn.microsoft.com/en-us/dotnet/api/system.exceptio...
The vast majority of cases, direct callers can't properly the handle the new error anyway. Callers either have to eat that exception, convert it (thus defeating the purpose of checked exceptions), or change their signature. Good programmers will change the signature and now every one of the callers of those methods have do the same thing. Ad infinitum.
However in small to mid sized enterprise software companies with average developer talent it’s important to keep boundaries (and blame) clear.
In the scenario in question, the CTO will blame OP and make them work the weekend to diagnose/fix it, so wrapping the other exception and throwing their own SomeModuleException will cover their ass.
Java is popular for all the wrong reasons. Believe it or not there are hundreds of such companies in the US alone heavily using Java in this manner and then there is the whole offshore development segment.
From operations’ point of view the bug will be pinned on the owner of the service that is returning the JSON to the client/app and it’s up to them to trace it down the layers. A hierarchy of wrapped exceptions helps with that. Kind of like saying “I can’t do it because XYZ didn’t do what they were supposed to do”. So low key corporate blame game in code.
I know that the usual HN crowd doesn’t work at/know about companies that follow this, but this pattern is way more prevalent in the broader “IT” industry esp among offshore centres.
On the other hand, a Result type makes errors part of the type system, and all other code can work with them "by default".
Unchecked exceptions, however, are a different beast entirely. They're not just checked exceptions without the checking; they fundamentally change how you code and how you think about error handling.
There is no magic language trick that can prevent you from having to rerun all tests for your software if you update a dependency. Pretty much period.
(I say this as someone that isn't really opposed to checked exceptions.)
Of course, but having a checked exception (even better, having the errors be part of the return type via Result<T, E> or Option<T>) solved an entire class of problem. Doesn't mean that there aren't others of course. But surely this is a win?
>inb4 it makes the code very complex with nested return type Result<Result<Result<T, FileNotFoundError>,ReadError>, ParseError>
Then it was just hidden from you before. The complexity had always been there, it just never occurred to you that it can happen.
Not when it creates more issues than it solves, which checked exceptions do.
Checked exceptions are an entire side channel to the type system which breaks any sort of composition or genericity.
Maybe this is solvable, but Java seriously poisoned that well because its implementation is so shit, and if you’re looking for this static safety, first the rest of a Java-style type system does not justify it (there’s so many low hanging fruits), and second a result-style things will already give you the same benefits in a form which is known to work.
Signals that don't unwind can have their own problems, of course. I don't mean that as a silver bullet. But all too often the exceptions and error conditions that we use to teach these ideas are far more difficult because of our insistence on unwinding the stack. Neither return values nor exceptions change that.
Hopefully, your answer is compile time. If so can you now understand why you would want to be alerted about a new exception getting thrown at compile-time as well?
As such, any breakage from calling would be, by definition, a bug. And no, we have not found a way to prevent bugs.
The library code can already throw anything. OutOfHeap, over/underflow, div0, stackoverflow, threadinterrupted. The caller already knows the function can throw, and documenting one more flavour of throw doesn't tell the caller anything.
but it does, in cases when there are errors that can or should be retried. Like a whitelist of documented cases where recovery and retry are possible, and of course all this infinite runtime stuff that can happen unexpectedly, for which there is no immediate solution.
I’ve seen too much code were some random problem in an Error - OutOfMemoryError for example when processing too much data (Eg call data records, payment records, analytic records, whatever). If it’s a batch processing job, you don’t want this problem for this specific entity causing the rest of your reports not to be sent.
I’ve also seen stupid things like RPC libraries silently swallow Errors and not report them properly to the caller, so we end up wrapping all RPC server endpoint methods in a try-catch-Throwable just so we can see the problem and log it.
If I’m processing a monthly report for millions of customers, I don’t want to abort processing after running into one problem customer. I want to continue to process the rest of them, and log the problem customers exception for troubleshooting and analysis offline.
Not necessarily. If it started throwing a new RuntimeException, it wouldn’t have. There are also sneaky ways to throw checked exceptions without declaring them, for example using Lombok’s @SneakyThrows annotation
Checked exceptions do nothing to protect against those kinds of mistakes, which in my personal experience are vastly more common than whatever mistakes for which they may provide some protection