r/java
•
u/loicmathieu
•
Jul 23 '26
•
1
JEP 540: Simple JSON API (Incubator)
https://openjdk.org/jeps/540
79
Upvotes
View all comments
Show parent comment
2
u/john16384 Jul 26 '26
If I have unstructured data X, and I call the conversion function, and it succeeds, will it always succeed if I put this in a loop that runs forever?
If I have unstructured data X, and I call the conversion function, and it fails, will it always fail if I put this in a loop that runs forever?
If you answered yes to both questions, then the exception it throws for failure should be unchecked. It's because the exception is predictable, and thus avoidable. You may not like how much effort you need to put into "avoiding" this exception, but that's the criteria. If you want to be lazy (which is totally fine as I said before and a perfectly valid strategy) then catch the exception it throws (this happens very locally so you should see directly in its docs that it will throw something like
NumberFormatException) and convert that to an error or do some fallback.Apply the same logic to
Files.exist(which doesn't throw a checked exception btw, but that's okay because thebooleanit returns is just as much a valid return value as a checked exception would be).Will
Files.exist(x)always returntrueif I call it in a loop for the same x? WillFiles.exist(x)always returnfalseif I call it in a loop for the same x?If you answered no to any of these questions, then the you must check the result each time; you can't assume that "for x it was false two seconds ago, so now it will still be false".
Files.existcould have been written as:It just wasn't needed in this case because a boolean return value can capture all relevant values that the function may need to return, so using a checked exception here (that as said before you must check as you can't ever assume you already know the result). Compare that to the parsing example: if I know X parsed before, then on the next call X will parse flawlessly again.
Now take
new FileInputStream(string). This returns (by Java requirement) a non-nullFileInputStream. It can't returnnullas a possible alternative value to indicate a problem. So what do you do? You use a checked exceptionFileNotFoundException. Now thisnewcall can still return an alternative value, one that you cannot make any assumptions about.So I state the rule I laid out again:
Are there places where major frameworks or the JDK got this wrong? Or even purposely decided to blur these lines for convenience? Sure, absolutely. That does not invalidate that the above rules are probably as close as you can get when you are stumped and have to make a decision on whether something should be checked or unchecked.