4 ms·
> Except, that’s all a lie. Because every function implicitly can throw RuntimeException and its children. Things like OutOfMemory or StackOverflow. > So basic
by dwaite 2y ago
> Except, that’s all a lie. Because every function implicitly can throw RuntimeException and its children. Things like OutOfMemory or StackOverflow.
> So basically all code everywhere realistically has to be aware of exceptions. A lot of people get lazy and don’t bother to list the actual kinds of exceptions they throw or pick one that’s a runtime exception so they don’t have to add the ‘throws’ to the signature to every single method.
Not just that, there are features like lambdas where the core language features were not designed with exceptions in mind. There are third party libraries which don't have allowances for proper failure cases. So you will have code adapted to wrap their exceptions into runtime exceptions for interoperability.
Of course, there's no guarantee the code which did not provide an interface which allowed for exceptions will not have unexpected side-effects when runtime exceptions or errors are being thrown.
> However there’s a lot of different kinds of exceptions. So very quickly you tend to end up with one of two things. Functions have a big list of possible exceptions (an A, or B, or C, or F, or G) or the far more common in company code: throws Exception. Don’t bother to list stuff, just say “I throw stuff”.
Ideally, someone creating an API thinks about how the others utilizing code will accomplish recovery or graceful failures, and craft an API to account for this. Unfortunately, the errors are often handed up, which really only accounts for broad failure behavior and corresponding cleanup (such as failing the corresponding HTTP request with a generic 500 error).
The heavy use of adapter patterns in Java means that the errors being handed up may be specific to the configuration, such as failures coming from the network layer of a database backend. It is crucial for the adapter interfaces to think about failure scenarios and recovery, but it unfortunately doesn't happen often very often.
So in most cases, Java should just throw Exception, because the only way a developer can really attempt recovery is to break encapsulation and operate based on knowledge of the inner workings of the object they were handed.