If it has nothing to do with your code, why not either let it bubble up the stack or try/finally it to do whatever clean-up you need to do before re-throwing it and letting it move on to a global logger or similar.
If it is something you care about you can always catch the specific exception type and handle it.
Maybe whoever worked on the other function wasn't even aware it might throw that particular exception.
Granted I am far more experienced in C# than Java, but the idea that with every code change you potentially have to review and declare every single type of exception seems like madness ("what happens if we pull the cord when it's here, what type will that throw?").
If there's a benefit to compile-time exception checking over this method, I have to admit I don't see it. But I've also never worked deeply enough with Java to be familiar with the nuances of its exception handling, so that may be why.
It's useful when there are one or two error cases you want to retry or handle specially, but you want to just barf any other error up the stack. It's a specific use case but it's prevalent.
The downside is that sugar can only separate your error conditions by Java type. If everything is just an Exception, you'll have to use sort out your error cases in code.
Being able to know what exceptions can possibly be thrown at a given point is useful, but seems like a problem better solved through static analysis than by requiring annotations.
That's why it is really useful to know when a call can fail, and what kinds of errors you have to expect.
If you always have to add a generic error handler for possible unknown errors, then you'll write a lot of untested, dead code.
Sure there is. Find the way it happens, do that, and test that the handler does what it's supposed to. Or, if you can't do that, mock the error.
I suppose that's not guaranteed to be straightforward in Java; it's been a long time but I seem to recall libraries being provided in compiled form, without sources, and it therefore not always being possible to identify the conditions that need to be set up in a unit test. If I recall that correctly, it makes me very glad I no longer use the language.
> If you always have to add a generic error handler for possible unknown errors, then you'll write a lot of untested, dead code.
The generic handler in this case is
else {
throw error; // rethrow
}
You're not wrong that there's value in knowing what exceptions can be thrown at a given point in code. But, as I mentioned in another comment, that's something that can in the general case be known through static analysis, and should. In fact, the Java compiler must already be doing something substantially similar to that analysis for checked exceptions to work at all! Looking for throw statements rather than "throws" declarations seems like it shouldn't be that much more difficult, and I think the burden on Java developers could be substantially lightened thereby in that "throws" declarations would no longer be required.In F# it works quite well, though.
You can write almost exactly the same code with your Result by ignoring the error until the point you would catch it with exceptions.
The only difference is that exceptions bubble up if unhandled, which requires a generic catch to match code ignoring errors otherwise.
It is quite a bit more explicit in that something can have an error and in what ways it can error (if you enrich the type in that way), while still being ergonomical. And it reserves exceptions for the truly unexpected/exceptional cases.
It's also pretty ergonomical depending on how you generally treat errors you don't care about.
I do find your point about exceptions being for unexpected things interesting: basically, split errors into two classes and use separate mechanisms for each.
I generally feel that this differentiation would never hold between different codebases (an HTTP library may consider network error something "normal", but users of that library might consider it exceptional), but it's surely an interesting concept.
I also think that we as developers are pretty bad at handling both expected and unexpected errors, so having two mechanisms will only make us less likely to do so (not by much, though).
FWIW, my take is that they are largely equivalent except for more or less syntactic support for the approach.
Yeah, as with lambda calculus and turing machines, they are equivalent in capacity.
> Are we comparing the same things? Adding exceptions to the method signature is pretty explicit to me too.
Maybe, maybe not. IME the IDE support for exceptions is quite a bit worse than for returning results and such.
> I do find your point about exceptions being for unexpected things interesting: basically, split errors into two classes and use separate mechanisms for each.
> I generally feel that this differentiation would never hold between different codebases (an HTTP library may consider network error something "normal", but users of that library might consider it exceptional), but it's surely an interesting concept.
Isn't the two ways to handle it already a thing with checked and unchecked exceptions, though? As in having wrappers that convert one to the other.
> I also think that we as developers are pretty bad at handling both expected and unexpected errors, so having two mechanisms will only make us less likely to do so (not by much, though).
I don't quite agree with that, as with encoding it in the type system conveys more intentionality than with exceptions, IMO.
Sure, but why keep using exceptions then at all? I am fine with returning errors making them explicit, but I would avoid exceptions everywhere (Go-style).
If it’s really recoverable, then should it actually be an exception? How often do you see exceptions that are recoverable?
> If not, then to avoid crashing you would have to catch the root Exception class, which everyone agrees is a bad idea.
I disagree that it’s a bad idea, having a catch-all exception handler to avoid crashing the entire app is a good idea.
Java also has RuntimeException, and with it, a whole host of exceptions that may occur but are not declared. Should every function that uses the division operator be marked with `throws ArithmeticException` since it may end up being a division by zero? That would quickly become absurd.
E.g. a network call failing due to some IOException can be easily retried, that’s a proper error handling.
You can try catching an OutOfMemory Error, but it is not guaranteed that your handling code can successfully run. Hence, non-recoverable.
That's the problem with exceptions in general. They're a hammer that makes everything look like a nail. People start using them for all kinds of control flow situations because they're more convenient than having to deal with a lack of type system support for optional values, etc.
You get to the point where you have a parser that is expecting a digit and it encounters an alphabetic character so it throws an exception!
In contrast, there are a billion ways in which almost every line of code can fail--even stuff people are super sure could never fail is still usually at least subject to stack exhaustion--and almost none of these failures are things you should locally "handle"; and yet in many--even most--cases these are situations you can still recover from at a higher level if you don't screw up your own logic (which is not the point of these errors).
For me it is much more ergonomic to use a
match tryparse somestring with
| Ok obj -> proceedFurther obj
| Error reasons -> handleerror reasons
For truly exceptional cases you don't expect to be recoverable? Yeah, throw an exception.Consider Files.createFile. It throws if the target already exists. That method has no way of knowing what the recovery is, however, the caller might.
It could be that the caller wants to explode, but maybe its part of some kind of singleton launch where the recovery is to pass some piece of data off to whoever created the file originally.
Maybe this is a bad example since there’s not much interesting in the return of Files. But it’s exceptional in that it’s an abort rather than a success.
That said, checked exceptions are still trash because they don’t work across thread boundaries or with futures. ExecutionException is the catch all baked into the design because they needed something. The idea could have been good though because naming error handling visible is useful. Java just has the misfortune of designing early before the kinks had been worked out and now we get nice stuff like Rust has.
Most of the time, it’s either catch the exception, log it in a central logging system keep moving and have a central alerting system or catch the exception log it and crash the program.
Something relevant to the error condition, probably?
There may be some cases where the total set of possible errors is too large to meaningfully handle every one of them specifically (for instance if you call a high level GPU initialization routine that can fail in a myriad of ways) but that's not true in all cases. Maybe the new error was in fact recoverable, or maybe it calls for some more specific diagnostics.
At any rate I completely agree with the parent that changing the set throwable exceptions should be considered a breaking API change and should be enforced by the compiler. If an API method wants to future-proof and be able to throw anything, it can declare just that and everybody will know to expect the unexpected.
That's why I vastly prefer Rust's Result<> system which does most of what exceptions do and with fairly similar ergonomics but with normal return values and all the type checking that it involves.
And in every language I know you can have catch blocks for specific errors and then have a generic catch all.
The parent apparently had exhaustive exception handling, catching all cases. A new exception is now generated, probably signaling a new error condition, you can't expect the calling code to be able to handle it gracefully.
Hence why a compile error might be a better solution here, the coder could decide whether the new exception can fit an existing handler or requires special handling.
If you're lucky you get a proper stack trace that lets you figure out what's going on, but even that is poor ergonomics.
A high level library should report high level exceptions for instance, not minute details of the lower layers. Nothing is more frustrating that having a program fail and all you have is some cryptic "No such file or directory" or "Operation not permitted" error that doesn't tell you what the code was actually trying to do or give you any hint on how to fix it.
See https://learn.microsoft.com/en-us/dotnet/fundamentals/code-a...
As a library writer, you should do something about exceptions that you can and rethrow the ones you can’t,
If your only goal is to avoid crashing the app then you can catch the base Exception class at the root of you code and go home. But consider the scenario that you're writing a very important method, where the functionality of your method is very important. If your method does not do its job, the rocket may crash or the patient may die. In this case you want to know what recoverable errors are possible in the functions that your method calls, correct? Wouldn't be it nice to get a guaranteed-by-compiler list of possible, recoverable, errors?
We all do.. its always that other guy who is at fault :)
It's a bad idea to catch an unexpected exception?
IMO the entire concept of "unexpected exception" is bogus in and of itself. That's like calling "exit(1)" in your code when something goes wrong instead of using proper error handling facilities.
Admittedly it's very convenient for small scripts where proper error handling might be overkill, but for any serious application it's a massive footgun IMO.
Anyway, I sympathize with this thread's OP, as I've had exactly the same problem with C#. In the end, I came to the conclusion you kind of do often have to catch every exception, because you can't trust the functions you call, and the documented exception lists for framework stuff are not always accurate. Safest is to put each call in its own try...catch block, and do any property accesses outside the try...catch block so you find out about the NullReferenceExceptions.
This is annoyingly verbose though.
It also does assume your setters and getters don't throw anything.
I mostly liked C#, but the exceptions aspect is not good. Similarly, I've generally despised working with Go, but the way it deals with errors is not its worst feature! (You do have to pay attention to the linter output though! It's the same err variable every time, so the compiler's fastidious checks for variable use are always foiled...)
You're applying a value judgement that the language makers can't and shouldn't make for you. Whether the error is innocuous or malicious, the happy path of your code cannot proceed and needs explicit handling by the programmer.
There is one case where the socket send succeeded, and another where it failed. There is one case where the file name encoding is valid, and another where it is not. And so on. It makes no sense, in my view, for one case to be handled with one language mechanism and the other case to be handled with another.
By comparison, there is (or so I claim!) no valid path where a null pointer is dereferenced, or where a value is divided by zero. So I will accept the requirement for some other mechanism for dealing with these - though by the time the code is released to the wild, I would hope that all such occurrences would have been eliminated.
The thing it really doesn't want to do is punt the issue on to some higher level. Because there isn't one.
But, equally, you don't want to be swallowing interesting problems that genuinely indicate actual bugs. Those, you do want to pass on (and due to the lack of any higher level, your process will be killed, and some mechanism will spring into action to produce a report).
Another issue is that you are not allowing higher layers see the exception, even though they may have logic for recovering from the exception. To see the exception they have to now fix your code by removing the catch-all.
Catching typed exceptions give you much more easily parsable details about whether or not “it’s possible” to recover.
It’s bad practice to catch the root exception. More often than not, it points to an inexperienced developer
Checked exceptions - a feature that seems to be a cost to the developer 100% of the time while being a benefit far less than 1% of the time - is a quintessential example of Java's tendency to cause developer fatigue.
The point is, if you don't need the rigor of a strongly typed compiled language, there are other languages you can use. Perhaps a bash script is all you need.
That a lot of languages force you to write it out is not an inherent property of strong typing.
Following your logic, Java developers can now say “if you don’t like freedom of Java, use Rust/Haskell/Scala to validate everything at compile time”
foo():boolean throws Some, List, Of, Errors
foo():boolean | Some | List | Of | Errors
foo():(boolean | nil) , (nil | Some | List | Of | Errors)
The first is checked exceptions. The second is returning different types. Typically there's some sort of Option wrapper for ergonomics. The third returns a result, err tuple and by checking if err is nil you can see if foo succeeded.
Ultimately they are all the same. What differs is the boilerplate/syntax to accomplish what you want. If what you want is a generic error to handle unknown events then you gotta write it that way no matter which system you use.
I wish C++ had checked exceptions.
Brutal, even for this site
Until very recently, Java was just tedious, repetitive, high-entropy language, where you had to write everything multiple times.
Eg.:
VeryLong<Type> variable = VeryLong<Type>();
In this expression, it's obvious what would be the most likely type of variable, but you still have to write it twice -- which is just worthless use of your time, especially when trying to read this very repetitive mess, and very easy to make a typo.Recently, Java tried to improve this situation by allowing to omit types when the type inferred by default is the one you want. So, you need to write less. You also need to learn the inference rules, obviously, so it increases the cognitive load and rises expectations towards programmer's skill a bit. But, I think it's fair, since Java from a language for the brain-dead transformed into a language that requires more effort to master. While I'm not sure it's a positive change... this decision by Java developers kind of flies in the face of your argument:
No, it's not necessary to repeatedly spell out what you want your program to do. It's just boring and contributes nothing to the program's correctness. If anything, it only causes the programmer to lose focus and introduces mechanical errors that would've been totally avoidable, had the language was more terse.
More than half a decade ago.
var fireable = someMethod();
firable.fire();
The programmer intended this code to fire an employee. Let's say this code is in a military application, and another programmer modified the someMethod() function to return a missile. As long as the missile object has a fire() method this code will compile just fine... and do something the code didn't intend to do.How likely are you to have employee firing and missile firing in the same program? Not very likely, but the principle is valid, regardless. You need to express your intention more clearly like this:
Employee fireable = someMethod();
Now if someMethod() is modified to return a missile you get a compilation error, and the world will be a lot safer. You don't want missiles being fired by accident!It's a ridiculous thing to worry about in either of your cases. That incredibly specific situation simply isn't ever going to happen in practice because so many other conditions need to be met for the compiler to let you proceed.
Not necessarily at all.
> unless the only thing you ever do to that object is call fire(), which is nonsensical
You can be calling other methods on the object in other places, but in one particular block of code you may be only calling fire(). And in that block of code, all the compiler cares is that the type has a fire() method. Thus the compiler is not doing a full check.
> It's a ridiculous thing to worry about in either of your cases.
Not at all... if your program is running inside a NASA rover, or if your program is running inside a robotic surgery machine you have to worry about safety and you want to maximize compile-time checks.
The point being, someMethod is doing some job that you want it to do. It is incredibly unlikely to simultaneously start doing a completely different job, while also returning something of the same shape.
If you intentionally break it, that's on you.
> It is incredibly unlikely to simultaneously start doing a completely different job, while also returning something of the same shape.
But it doesn't need to return something of the same shape! The shape is not being checked. All the compiler checks is for the existence of a single method of the same name. You call that type checking?
> If you intentionally break it, that's on you.
The shape is not being checked. All the compiler checks is for the existence of a single class of the same name. You call that type checking?
You should be insane if your program accidentally confuses people with missiles, but I understand that this is a stretch to amplify the point. What tends to happen in practice is that eg. the same method which used to only read something from the local storage gets a new overload that goes out into network, and brings with it a whole new bunch of problems the calling code wasn't prepared to handle. Or, when a string was passed to the method that used to do something simple, and then the method gets overloaded with a more sophisticated method that interprets substrings in the passed string as commands to run some code -- and then you get security problems.
Have you ever seen the IntelliJ interface when it deals with Rust code? I'm not sure if it does the same for other languages with type inference feature. Anyways, the idea here is that the programmer can toggle the display of inferred types to qualify every expression. So, it's really trivial to make sure you aren't calling fire() of a missile instead of an employee. And, in practice, this doesn't lead to problems. This is so because dispatch, essentially, blurs the difference between multiple different objects, while type inference is just a kind of abbreviation. It may cause confusion, but it will be of a different type: the reader might not know what's being abbreviated, whereas with dispatch, the reader may be convinced they know what the author meant, but still be wrong.
That's a terrible solution. Eyeballing is not as reliable as compiler doing a check. The language should provide a way for the programmer to express intent, and the compiler should do the check.
You can express intent more clearly when you say:
Employee foo = someMethod();
as opposed to: var foo = someMethod();
A real-life example: I once helped a kid with her Python program to sort numbers. I looked at the code and the algorithm seemed correctly implemented, but the output was incorrect. The bug turned out to be that she hadn't called int() to convert the user input to integer, so all of the data passed through the entire program as strings, and got sorted as strings. There was nowhere in the code where the programmer could express intent that this is supposed to be integers. This sort of thing would never have happened in Java. Well, unless you misuse 'var'.I would love if, at design time, all the possible exceptions that could happen were able to be inferred. But, the way it happens in java, it's entirely manual, and it won't catch things where I'm referencing compiled code.
This has nothing to do with strongly typed compiled languages vs alternatives.
That's because exceptions are overused for not-truly-exceptional conditions. Languages that throw exceptions when a dictionary does not have a key you're looking for are doing it wrong.
That's exactly it. A holier-than-thou stance, reprised by most comments in this post.
Checked exceptions were a PITA.
Someone has recommended to use another language if you didn't like it. Unfortunately my employer at that time had entered a partnership with Sun that prevented that :)
Another ideological prohibition: no pointers. Well, how do you assign event handlers then? People were extremely confused with anonymous classes. I got the reason instantly.
I call BS here. I've worked in a few Java projects, and in every single one, the people changing the method in question would have thrown RuntimeException to stop the compile errors.
If RuntimeException was checked, you might have a point, but given that there's a class of unchecked exceptions, you're relying on discipline instead of the compiler anyways.
Seriously, Java doesn't force bad programmers to write good code. It just enables good programmers to write good code.
I will also cede the point that you can write good code in Java.
But my point was that Java wouldn't have enforced the situation to be a compile error, not that you can't write good code in Java. I maintain this point, and I think it's true for the average java project.
If you're getting these benefits from Java, it's the intersection of Java and your team's or your organization's culture, not purely from Java. It's possible for you to gain this benefit and for checked exceptions to have still failed out in the wider world of the average Java project.
No... I don't think so.
Checked Exceptions are at best, just a 'hey, are you sure that's right thing to do here?' and at worst, an additional source of rigidity in your code that blows up the scale of a minor change.
Right, and that was my point at the top post in this thread.
Also, imagine a situation when an iterator throws an exception. Or you wanted to write f(g()) but now you can't and have to do:
try:
T t = g();
catch E1:
...
catch En:
...
f(t);
Now it takes a much greater effort for the reader to figure out what's going on. It's also tempting to allow some exception cases to succeed so, f(t) is reached even if there was an error. Because these two code pieces are now far apart, it's possible that later edits will introduce bugs because the programmer didn't see that either f(t) is reachable even if g() failed, or accidentally made it reachable when it shouldn't have been.Bottom line, it makes human errors more likely.
try {
final var fResult = f(g());
//do something with fResult
}catch (E1 e) {...}
catch (En e) {...}
That's the main idea of exceptions in all languages: main flow is kept together and exceptional flows are separate.
You cannot have both at the same time, I'm afraid.
How are you going to write generic functions that take functions as arguments and re-throw the errors thrown by these functions, if you use checked exceptions? Will you require that the acceptable functions only throw exceptions that you like? -- Then your generic function is close to being worthless...
If exceptions are encoded in function's interface, then they have to be in ABI, but then you must have non-trivial types available when marshalling data between two components, so, you cannot serialize the communication using some protocol with a fixed number of types (eg. JSON and friends), because now you need to account for the infinite variety of exception types.
Because of at least these two things, what I saw happen a lot of Java / C++ projects (god blessed me with very little C# exposure) was that as soon as a developer encountered a function with checked exceptions, a wrapper was written which changed the type into a runtime exception. This is so because exceptions are supposed to be handled separately, and often the author of the function has no idea how they need to be handled -- so they want to concentrate on the main goal of the function. Once functions grow into garlands of try-catch-catch-catch-...catch the focus is lost. It becomes very hard to understand why the function was written in the first place, because the error handling takes over every other concern.
Constrained generic parameters are actually super useful.
> If exceptions are encoded in function's interface, then they have to be in ABI
They already are in Itanium
> you cannot serialize the communication using some protocol with a fixed number of types (eg. JSON and friends), because now you need to account for the infinite variety of exception types.
No, the only exception that arises is ser/deserialization error. You can also trivially represent an error in JSON using an object, which is exactly what JSON RPC protocols do. It's also never safe to throw across an FFI boundary and similarly nonsensical to throw across a serialization boundary, so I'm not sure why you'd care.
Then you missed the main point: if you require the generic function to accomodate all sorts of kinds of exceptions raised by the functions it may call, this requirements now propagates to every function it may call. So, you end up implementing functions with unnecessary "throws" because they might be used in a generic function which had to add that clause because of some other completely unrelated function.
Alternatively, you aren't writing generic code at all, you just write two implementations which happen to have similar names.
There is a philosophy that applies here: simple things should be simple, complex things should be possible. The scenario you're mentioning is not common enough that the language design should be centered around it.
... so the basic "catch" syntax starts to fall apart because now you have to catch everything and resort to stuff like Guava's Throwables helpers.
It's madness.
The problem ultimately is variance: Methods are covariant, but throws clauses must be contravariant.
There are ways to solve this but "checked exceptions" (as in Java) are not the right way. Ask anyone who's worked in Scala on the JVM which they prefer and you'll have your answer.
It really is a lose-lose unless Java grows a more powerful system around this.
Re-throwing a non-checked exception is what I described as the usual / typical coping mechanism in languages with checked exceptions. Which is obviously a way to negate the whole feature.
Wait. Why should a map care about what exceptions it's arguments can throw?
A map is storing a thingit. A thingit should exist independently before it gets placed into a map. Placing a thingit into a map should not invoke anything on the thingit. The only exceptions coming back from attempting to place a thingit into a map should be exceptions caused by the map.
What am I missing?
Obviously, there are maps that conflate themselves and do things like take ownership when an object is placed into the map. But that's not the general case and presumably you wrote the map specifically with that in mind.
The map function takes a function and a list and applies the function to every element of the list:
map double [1,2,3] = [2,4,6]I've actually done this with an interface type parameter used in a throws clause in Java before, but I'm not sure how it interacts with module boundaries, it's kind of verbose, and it certainly didn't seem to be common practice. But it did work: the HOF-ish method that took a parameterized ThingFrobber<E> and used it to frob things unchecked would compile only if it also threw E, and the method passing the HOF a ThingFrobber (I think via lambda syntax) could catch the associated concrete checked exception type to sink it. IIRC I was using it to allow a checked early exit from a complex iteration, and it even propagated a slightly complex bound with multiple checked exception types more smoothly than I'd expected it to.
Just make your ExampleInterface generic -- ExampleInterface<T>.foo() throws T.
That technique works really well, and I don’t understand why it isn’t more widely used (or at least it wasn’t when I last used Java for serious work).
Each non-leaf statement is a composition of leaf statements. Therefore every exception can be determined, and that's our checked exceptions would work; work at the exceptions and check they match the list.
Therefore even without checked exceptions the compiler could provide the exceptions you want and you can check them or not if you please, so get the best of both worlds. All without forcing people to give an explicit list of exceptions everywhere. Forcing checked exceptions is not going to be popular, and much of the time is counter-productive.
Also someone broke your Liskof Substitution Principle which may be your bigger problem.
As an example, I wrote some very good C# code, carefully tested it, made it work flawlessly, then suddenly it started crashing. What happened? Someone made a change in a function I was calling, and it started throwing a new exception. This would have caused a compile error in Java, not a crash.
The list of recoverable exceptions that can be thrown by a method should be part of the contract. It should be written down by the programmer, and enforced by the compiler. If not, then to avoid crashing you would have to catch the root Exception class, which everyone agrees is a bad idea.
More on checked vs unchecked exceptions here: https://forum.dlang.org/thread/[email protected]...