This is a created article in which the information may have evolved or changed.
How to deal with exceptions this problem has plagued me for a few weeks, write some of my own feelings
Why should there be an abnormal mechanism?
① in the traditional language C language, when you manipulate resources, it is generally through the function return value code to determine whether the execution succeeds (generally, the failure returns an integer less than 0).
② scripting languages, such as Python, PHP, etc., are generally return false on failed because there is no restriction on the return type. Of course, these scripting languages also have an exception mechanism.
③ multiple return value language (Golang), typically by returning multiple values (which may contain an Error object), and then using the error value to determine whether the operation was successful.
Second, summary
As can be seen from the above examples, ① return error code ② return false and so on, these error messages are not clear enough, many times also avoid layers of nested judgment in the vortex. ③ 's way is good, but every time you have to check the error
As a static language, Java is a single return value, the return type is determined, when an exception cannot return the specified type (of course, you can return null or empty object, but generally not recommended to return null), this time the exception mechanism can be a good solution to this problem. The function caller simply cares what the call to this function will return, whether the exception requires this layer of processing or continues to throw up, can greatly reduce the burden on the caller (if you do not need this layer of processing, I only need to care about what the API will return, write their own logic down, do not need check error, Resource release recommended using Try-with-resource)
However, if it is unchecked exception, you must indicate in doc what exception the function throws so that the caller can use it, whether it's Java, Python, or PHP.