Unless it's a last resort, don't catch!

Source: Internet
Author: User

"Editor's note" author Yegor Bugayenko is a software architect for Teamed.io, keen on software quality research and effective project management approach exploration. In this article, Yegor discussed the issue of "exception caught but not re-thrown" and shared some suggestions.

It's a common and very popular mistake to just catch an exception and not re-throw it anti-pattern. But there's no doubt that in all exception capture code, it's basically everywhere, as in this code:

    try{      stream.write(data);    }catch{      ex.printStackTrace();    }


Note: The following code has no objection.

    try {      stream.write(‘X‘);    catch (IOException ex) {      thrownew IllegalStateException(ex);    }

This is called exception chaining and is a very effective construct.

So, catch the exception and record what kind of problem exists? First, from the macro level, what is being discussed here is object-oriented programming-meaning that objects need to be addressed. An object (to be exact, its class) should look like this:

    final class Wire {      privatefinal OutputStream stream;      Wire(final OutputStream stm) {       this.stream = stm;     }     publicvoidsend(finalint data) {        try {          this.stream.write(x);        catch (IOException ex) {          ex.printStackTrace();        }      }    }

Here's how to apply this class:

new Wire(stream).send(1);

It looks good, right? When called send(1) , there is no need to worry about IOException it, it will be processed inside the method. Also, if an exception occurs, the exception information is logged. But the idea of doing so is completely wrong, and it is inherited from languages that have no exception handling, such as C.

The exception was invented to simplify the design by removing the entire error-handling code from the primary logic. At the same time, they are not only removed, but are concentrated in one place-in the main() method, the entrance to the entire application.

The main purpose of an exception is to collect as much error information as possible and throw it to the top, where the user can do some processing on it. Exception chaining can help more by allowing the error message to be extended in the process of throwing an exception to the upper layer. In this process, it is very similar to the fact that every time you capture a bubble (that is, an exception), all you do is add it to a larger bubble and then re-throw it. When it reaches the highest level, there are a lot of bubbles, like a Russian Doll, with one nested in another. The most primitive anomaly is the smallest bubble.

When you catch an exception and do not re-throw it, it is the same as you crush the bubble. It contains a lot of information, including the most primitive anomalies and all the other bubbles with information that you hold firmly in your hands. You stop presenting it for the top, and you're unaware of how you handle and use the upper layer. It's all like a black-out operation, and some potentially important information is hidden.

Therefore, the direct result here is that the method cannot be trusted, and the send() same method-based send() operations cannot be trusted, and the chain of trust between the objects is destroyed. The suggestion here is to catch as few exceptions as possible and to throw them once they are captured.

Unfortunately, Java's design in many places violates this principle. For example, Java has two types of exceptions that need to be checked and not checked, but in my opinion there should be only exceptions that need to be checked (these exceptions must be captured or declared as Throwable). Also, Java allows multiple exception types to be declared as throwable--in one method; this is another error; insist on declaring only one type. There is a generic class at the top of the hierarchy Exception , which in my opinion is also wrong. In addition, some built-in classes do not allow any exceptions to be checked, for example Runnable.run() . Java also has a lot of questions about exceptions.

But try to remember these principles and your code will be cleaner: catch unless you have no choice.

P.S. This class should look like this:

    final class Wire {      privatefinal OutputStream stream;      Wire(final OutputStream stm) {        this.stream = stm;      }      publicvoidsend(finalint data)        throws IOException {        this.stream.write(x);      }    }

Original link: Catch Me If you ... Can ' t do Otherwise

This article is compiled and collated by OneAPM engineers. OneAPM is an emerging leader in application performance management, enabling enterprise users and developers to easily implement slow program code and real-time crawling of SQL statements. To read more technical articles, please visit the OneAPM official blog.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Unless last resort, don't catch!

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.