...
Feedback can also be provided by throwing either standard or custom exception objects derived from the Exception
class. With this approach, the developer can still get precise information about the outcome of the method and proceed to take the necessary actions. To do so, the exception should provide a detailed account of the abnormal condition at the appropriate abstraction level.
To gain better ability at telling apart correct from fallacious results and enforcing that the incorrect results be carefully handled, a combination of the aforementioned approaches is recommendedAPIs should use a combination of these approaches both to help clients distinguish correct from incorrect results and to encourage careful handling of any incorrect results. At the same time, in some cases, an error value instead of an exception should be returned, and vice versa. For instance, if some method is capable of failing in a variety of ways, it is better to return failure codes than try to throw scores of different exceptions. Note that no all possible failure codes should be within outside the range of valid return values.
Sometimes Alternatively, an object can provide a state-testing method [Bloch 2008] can be used to ensure that checks whether the object is in a consistent state at all points in time. This approach is not useful only in the absence of combination with external synchronization. There is also Lack of appropriate synchronization leads to a time-of-check, time-of-use (TOCTOU) race condition between invocation of the object's state-testing method and the call to a method that depends on the object's state. During this interval, the object's state could change surreptitiouslyunexpectedly or even maliciously.
A method should not return a value or error code that does not Method return values and/or error codes must accurately specify the object's state at an appropriate level of abstraction. Clients should must be able to rely on the value for performing critical decisions.
...
As shown in this example, noncompliant methods can silently corrupt the state of the object if they do not fail to return a value that the developer can intuitively interpret.
...
Failure to provide appropriate feedback through a combination of return values, error codes, and exceptions can lead to inconsistent object state and unexpected program behavior.
...