Improve the quality of your Java code: Advocate exception Encapsulation

Source: Internet
Author: User

I. Analyzing the Exception Handling Mechanism in Java can ensure program robustness and improve system development efficiency, however, exceptions provided by Java APIs are relatively low-level (here the low-level refers to "low-level exceptions"). Only developers can understand the issues and understand what has happened. For end users, these exceptions are basically tianshu, which is unrelated to the business and described in pure computer language. This requires us to encapsulate the exception. Ii. Advantages of abnormal scenario encapsulation: 1. improve the friendliness of the system. For example, if a file is opened and the file does not exist, the FileNotFoundException exception will be reported. If the method is written without any processing, throwing the upper layer directly will reduce the friendliness of the system, the Code is as follows: [java] public static void doStuff () throws Exception {InputStream is = new FileInputStream ("invalid file .txt "); /* file operation */} doStuff method is extremely friendly at this time: When an exception occurs (for example, the file does not exist), this method directly throws the FileNotFoundException exception to the upper-layer application (or end user ), the upper-layer applications (or users) either process them by themselves or throw them. The final result is to make the users stay in the text of the "tianshu" style, and the users do not know what the problem is, the system only told him. "Oh, I made an error. What is the error? You can do it yourself." The solution is to encapsulate exceptions. The readers of the system can be divided into two types: developers and users. The developer needs to print the stack information to find the problem, and the user needs to understand the specific business reasons, such as the file is too large to write files at the same time. The Code is as follows: [java] public static void doStuff2 () throws MyBussinessException {try {InputStream is = new FileInputStream ("invalid file .txt");} catch (FileNotFoundException e) {// exception information set to facilitate development and maintenance personnel e. printStackTree (); // throw service exception throw new MyBussinessException (e) ;}} 2. improve system maintainability [java] public void doStuff () {try {// do something} catch (Exception e) {e. printStackTrace () ;}} This is an easy mistake for many programmers. Is it true to throw an exception? If classification processing is too complicated, write a catch Block to handle all exceptions. I also vowed to say that "JVM will print the error message in the stack". Although there is no error, this information can only be understood by developers themselves, the maintenance personnel cannot handle this exception because they need to go deep into the code logic to analyze the problem. The correct method is to classify exceptions and encapsulate the output. The Code is as follows: [java] public void doStuff () {try {// do something} catch (FileNotFoundException e) {log.info ("folder not found, use the default configuration file .... ");} catch (SecurityException 3) {log.info (" no access permission, probably because .... "); e. after printStackTrace () ;}} is packaged in this way, the maintenance personnel can make a preliminary judgment on this exception, or check the configuration or initialize the environment, you do not need to go directly to the code level for analysis. 3. solve Java exception mechanism's own defects Java only throws one exception at a time. For example, the doStuff method has two logic code snippets. if an exception is thrown in the First Logic snippet, then the second logical segment is not executed, and the second exception cannot be thrown. So how can we throw two exceptions at a time? In fact, you can solve the problem by using a self-encapsulated exception. The Code is as follows: [java] class MyException extends Exception {// accommodate all exceptions private List <Throwable> causes = new ArrayList <Throwable> (); // constructor, pass an exception List public MyException (List <? Extends Throwable> _ causes) {cause. addAll (_ causes) ;}// read all exceptions public List <Throwable> getException () {return causes ;}} the MyException exception is only an exception container and can accommodate multiple exceptions, however, it does not represent any exception. It solves the problem of throwing multiple exceptions at a time. The specific call is as follows: [java] public static void doStuff () throws MyException {List <Throwable> list = new ArrayList <Throwable> (); // try {// Do something} catch (Exception e) {list. add (e);} // try {// Do something} cat Ch (Exception e) {list. add (e);} // check whether it is necessary to throw an exception if (list. size ()> 0) {throw new MyException (list) ;}} in this way, the caller of the doStuff method can obtain multiple exceptions at a time, it can also provide users with a complete exception description. Under what circumstances does one method need to throw multiple exceptions? For example, when registering a Web interface, the presentation layer transmits the User object to the logic layer in sequence. The Register method needs to verify and Register each Field. For example, the User name cannot be repeated, the password must comply with the password policy. do not submit the password for the first time. The system prompts "Duplicate usernames". After you modify the password, the system prompts "six characters less password, this operation mode has a poor User experience. The best solution is to encapsulate exceptions, create abnormal containers, verify the User object at one time, and then return all exceptions. 3. We recommend that You encapsulate exceptions based on the actual situation and needs during development.

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.