Returning error codes leads to deeply nested structures.
If the keyword try exists in a function, it should be the very first word in the function and there should be nothing after the catch/finally blocks.
The checked exception is an Open/Closed Principle violation. If you throw a checked exception from a method in your code and the
catchis three levels above, you must declare that exception in the signature of each method between you and the
catch. This means that a change at a low level of the software can force signature changes on many higher levels. The changed modules must be rebuilt and redeployed, even though nothing they care about changed.
Encapsulation is broken because all functions in the path of a throw must know about the details of that low-level exception.
Checked exceptions can sometimes be useful if you are writing a critical library: You must catch them. But in general application development, the dependency costs outweigh the benefits.
Each exception that you throw should provide enough context to determine the source and location of an error.
We should simplify our code considerably by wrapping the API that we are calling and making sure that it returns a common exception type.
Returning null maybe leads to deeply nested structures.
It’s easy to say that the problem with the code above is that it is missing a
nullcheck, but in actuality, the problem is that it has too many. If you are tempted to return
nullfrom a method, consider throwing an exception or returning a SPECIAL CASE object instead.
Returning null from methods is bad, but passing null into methods is worse. Unless you are working with an API which expects you to pass null, you should avoid passing null in your code whenever possible.
We’ll get a NullPointerException if a caller passes a null parameter.
How can we fix it? We could create a new exception type and throw it:
It’s good documentation, but it doesn’t solve the problem. If someone passes
null, we’ll still have a runtime error.
In most programming languages there is no good way to deal with a null that is passed by a caller accidentally. Because this is the case, the rational approach is to forbid passing null by default. When you do, you can code with the knowledge that a null in an argument list is an indication of a problem, and end up with far fewer careless mistakes.