About exception Handling

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.