Do not Catch unless you have !, Catch

Source: Internet
Author: User

Do not Catch unless you have !, Catch

[Editor's note] the author Yegor bugayko is a software architect of Teamed. io, keen on software quality research and effective project management methods exploration. In this article, Yegor「 Exception caught but not thrown again 」This issue was discussed in depth and some suggestions were shared.

It is a common and very popular error that only captures exceptions but does not throw them again. But there is no doubt that, in all the exception capture code, it is basically everywhere, as in the following code:

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


Note: The following Code has no objection.

    try {      stream.write('X');    } catch (IOException ex) {      throw new IllegalStateException(ex);    }

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

So what are the problems with capturing exceptions and recording them? First of all, starting from a macro perspective, we are talking about object-oriented programming, which means that we need to process objects. An object (accurately speaking, its class) should look like this:

    final class Wire {      private final OutputStream stream;      Wire(final OutputStream stm) {       this.stream = stm;     }     public void send(final int data) {        try {          this.stream.write(x);        } catch (IOException ex) {          ex.printStackTrace();        }      }    }

Here we will apply this class:

new Wire(stream).send(1);

Looks good, right? Whensend(1)You do not need to worry aboutIOExceptionIt will be processed inside the method. In addition, if an exception occurs, the exception information is recorded. However, the idea of doing so is completely wrong. It inherits the language without exception handling, such as C.

The exception was invented to remove the entire error handling code from the main logic to simplify the design. At the same time, they are not only removed, but also concentrated in one place-inmain()Method, that is, the entrance to the entire application.

The main purpose of an exception is to collect as many error information as possible and throw it to the top layer. Here, you can handle it. Exception chaining can help more. It allows you to expand the error information when the Exception is thrown to the top layer. In this process, it is very similar to adding a bubble to a larger bubble and then throwing it again after capturing the bubble (that is, an exception. When it reaches the highest level, there are many bubbles, such as a Russian Doll, one nested with another. The most primitive exception is the smallest bubble.

When an exception is caught and it is not thrown again, it is equivalent to crushing the bubble. It contains a large amount of information, including the original exceptions and all other information bubbles, which are firmly put in your hands. You should not present it to the upper layer, and you are unaware of how to handle and use the upper layer. All of this is like a dark box operation, and some important potential information is hidden.

Therefore, what is directly caused here issend()Methods cannot be trusted.send()The operation of methods cannot be trusted, and the trust chain between objects is destroyed. We recommend that you capture as few exceptions as possible and throw them once 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 do not need to be checked, but in my opinion, there should be only exceptions that need to be checked (these exceptions must be caught or declared as throwable ). In addition, Java allows multiple exception types to be declared as throwable in a method -- this is another error; insist that only one type is declared. There is a commonExceptionClass, which is also wrong in my opinion. In addition, some built-in classes cannot throw any exceptions to be checked, for exampleRunnable.run(). Java has many exceptions.

But if you try to remember these principles, your code will be more neat:catchUnless you have no choice.

P.S. This class should look like this:

    final class Wire {      private final OutputStream stream;      Wire(final OutputStream stm) {        this.stream = stm;      }      public void send(final int data)        throws IOException {        this.stream.write(x);      }    }

Source article: Catch Me If You... Can't Do Otherwise

This article is compiled by OneAPM engineers. OneAPM is an emerging leader in the application performance management field. It helps enterprise users and developers easily achieve slow real-time crawling of program code and SQL statements. For more technical articles, visit the official OneAPM blog.

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.