6 ms·
Didn’t Java require all exceptions be declared in the method signature? (Haven’t used it in years.) I think that’s the best solution. You declare what error co
by fuzzy2 7y ago
Didn’t Java require all exceptions be declared in the method signature? (Haven’t used it in years.)
I think that’s the best solution. You declare what error conditions could arise, but not using magic numbers. The caller can then decide whether to handle them or pass them to its caller etc.
I agree that unexpected exceptions (like it’s possible in C# and possibly others, you can just throw whatever whenever) are far from optimal.
- ramblerman 7y agoInitially yes, but this is somewhat unpopular these days as it means you have to daisy chain a new exception all the way up the stack if you can't handle it locally. Most have switched to runtime exceptions, which are more flexible in that regard.
- riwsky 7y agoNo. Only a certain subset, known as “checked exceptions” (as opposed to “runtime” exceptions), need to be in the signature. In what may come as a surprise, checked exceptions are actually frowned upon in modern java (e.g. new stdlib apis tend to avoid them). They do not compose very well with the rest of the type system (e.g. you cannot write a ”map” function that is polymorphic over checked exception types)—or at the very least, do not compose as well as some other patterns, like Optionals
- fuzzy2 7y agoHm okay. If it’s not “compatible” with streams, higher-order functions and whatnot I can see why it’s not popular. A pity, really.
- mrkeen 7y agoChecked exceptions sound good on paper. In practice I think I re-threw every checked exception as unchecked. In retrospect I feel like 'handling' exceptions is a myth. If you knew how to handle them, they wouldn't be exceptional.
- tsimionescu 7y agoChecked exception interact poorly with higher-order functions, but are otherwise pretty nice in my experience. If Java had a more powerful type system to allow it to abstract over exception type, it may have been a much more liked feature. Regarding handling, in my experience the vast majority of code has no way of handling an error (whether we're talking about exceptions or error-codes or Result<T, E>) except for logging and returning it up the call stack, or immediately aborting soemtimes. But there are places in the program where there rely is enough information to handle an error from a whole sub-module, usually by retyping with other params, by asking the user for advice, or by simply telling the user that something they did was wrong. Getting the right amount of error information to this place is the problem that exceptions solve the best in my opinion.