More on checked vs unchecked exceptions here: https://forum.dlang.org/thread/hxhjcchsulqejwxywfbn@forum.dl...
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.
I disagree with their point though, in java the lib would've probably just converted the exception to a runtime exception so the API doesn't change...
That'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();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.
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.
I don’t think that’s close to sufficient to making checked exceptions work tho, let alone good.
Sometimes, your logic is flawed. A condition occurs which you erroneously deduced not to be possible.
Unchecked exceptions are the necessary manifestation of these unforeseen errors. Catching them is pointless, what will you do with them? Dynamically fix the logic of your program? What can be the reasonable response to "index out of bounds", try a different index? [1]
Depending on the domain it may be appropriate to convert them indiscriminately to checked exceptions at module boundaries (e.g. requests within a server) -- but within said module it remains pointless to catch them. (This is a form of swallowing.)
In other domains, crashing is the correct behavior. The code cannot proceed correctly, it must abort.
Checked exceptions are appropriate only when the exception can be anticipated and thus planned for, ideally by code closest to where it is thrown.
[1] Actually there was a paper a long time ago that monkey-patching C code to return fake "null" data in response to out-of-bounds memory accesses actually resulted in the intended (i.e. correct) behavior in the majority of cases. But I digress.
When recovery should not be attempted (example: "index out of bounds") then you don't want to declare or catch the exception, and that's when you use a subclass of RuntimeException in Java.
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.
Is it worth it to thread the IOException through the network layer, then the HTTP-client library, then then business serialisation up to the actual context?
I don't want a dozen checked exceptions. (and with this approach socket-limitations and connection loss should get a different exception.) I also don't want catch and rethrow. Unchecked+checked+docs+crashes are a measured approach.
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.
Ah, but what if it can occur, just never with what you pass in? Suppose a function is documented to throw some checked exception if some parameter is a negative number, but you pass in a positive literal/constant? In such a situation, the checked exception will never occur! With Rust, for example, this is easily done with an `unwrap()` (and, possibly, a comment) to assert said belief, but with checked exceptions, there's no way to force the compiler to squash the required check.
The algebraic data type equivalent of this shows up all the time in functional code -- unwrapping a result type you know can't be Error/None/etc. because of logic. You don't rewrap it and force the caller to deal with a case which logically cannot occur; instead you throw an unchecked exception.
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.
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.
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 swallowedWho does that? It looks like an anti-pattern.
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.
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.
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.
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.
But really the problem is actually far worse than that. Checked exceptions are brittle under any kind of implementation change. If you have a function that calculates a rate just using arithmetic. But tomorrow it loads a flat file. And next week it uses SQL. And in a month it calls a web service. As a consumer, this is none of your concern -- that's the whole point of abstraction. It's even worse when dynamic (polymorhphism) or functional (external code calls you).
What's the recovery from a SQLException anyway? How does that give you enough detail to do anything? You say SQLIntegrityConstraintViolationException but that's not the same type. Why does it matter that you declared it a SQLException over just Exception in that case?
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.
Exceptions can be thrown from anywhere. That's the documentation.
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)
You should always be able to handle an unknown exception. Sure you can't do much about it, but it shouldn't be a big deal. An exception only occurs if the code can't continue as expected.
Libraries are supposed to be a point of abstraction. They should be allowed to change their implementation fundamentally as long as they continue to respect the same interface. Exceptions should not be part of the interface explicitly because are they implementation-detail related.
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.
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.)
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?
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.
As such, any breakage from calling would be, by definition, a bug. And no, we have not found a way to prevent bugs.
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.
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.
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.
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
But that's a major flaw with checked exceptions – very often, whether an error is recoverable or not depends, not on the API itself, rather on how it is used. Yet checked exceptions force the API designer to make that decision while designing the API, when they can only guess at how it will be used.
A good example of this is FileNotFoundException – whether that is a recoverable error which ought to be handled, or whether there is nothing better to do than crash, depends on what the file is. If we are implementing a File Open dialog box in a GUI app – okay, we better catch the FileNotFoundException and display an error box, not just crash. But, suppose I am writing a micro-service, and the first thing it does on startup is read its config file, and the config file isn't there: is there any point in trying to handle that exception, or should it just crash? Obviously the designers of Java's file IO classes had the first scenario in mind more than the second, but it is an inherent flaw of checked exceptions that they forced them to make this decision at all.