Advantages and defects of Java exceptions and their handling principles

Source: Internet
Author: User

Recently, I am working on a framework for reading database metadata. The database check exceptions are impressive. Try-catch is crazy. At the same time, when exceptions in the framework should be thrown to the caller and which ones should be handled by themselves, check exceptions or non-check exceptions are worth pondering. Many of the following are my opinions. I hope you can add and point out the mistakes. Java philosophy: poorly structured Code cannot run. (Generics do poorly) Advantages: 1. eliminate arbitrary factors in the error handling process in a mandatory form; (No one checks the C language printf, scanf will ). 2. It can reduce the complexity of error handling code. (Too much if-else is not required) 3. Carrying information makes it easy to detect problems. (Benefiting from the powerful StackTrace stack trajectory) What is exception? In the current environment, the necessary information cannot be obtained to solve the problem, and it will affect the current method or scope to continue the execution. In the first half of the sentence, if you cannot solve the problem, you can handle it at the next level. The so-called throw exception. If you can solve the problem, it is your program. In the next half, you can handle minor exceptions (to leave information). log4j cannot find properties and cannot directly crash the system. If an exception is thrown inside the Try block method, this method ends (throws to a higher level ). If you do not want to end, you can use try block. Try is to handle the same method that may be thrown in a centralized manner. In a language without exception handling, you may need to constantly check whether each operation is correct. in Java, you can perform concentrated processing. This corresponds to the exception advantage 2. Exception description (check the origin of the exception) Java encourages people to inform the client programmers who use this method of exceptions that may be thrown by methods. Void f () throws TooBig, TooSmall, DivZero describes method f. If yes, only the preceding three exceptions are thrown (except RuntimeException ). Java considers this kind of elegant practice, but it has become a lot of criticism. IO, database operations, the program will contain a large number of exception handling. If the program is very large, try-catch-finally is a disaster. In Spring jdbc, JdbcTemplate converts all database exceptions to DataAccessException exceptions and converts them to a Runtime exception. The reason for its secondary encapsulation is that you do not need to care about the details of a specific database, and you do not need to force the user to use try-catch. In the thrown exception, it saves the original information, the so-called exception chain. This is very important. The exception chain is very useful for debugging personnel. Hibernate's SchemaExport is a bad design. JdbcTemplate also prevents some exceptions that cannot be handled, such as database connection disconnection exceptions, even if they are thrown to the upper layer. The upper layer cannot be processed. It is better to catch it and then output it in the form of logs. Usage tips or Attention 1. resources to be released must be placed in finally. The code in the finally block must be executed. If the code is run, return exists in try, but "still" is output. Therefore, when the program contains database connections, I/O, network connections, and other resources that need to be released, use finnally to avoid unnecessary consumption. Copy the code Int f () {try {return 0;} finally {System. out. println ("ended") ;}} the code was copied before hibernate4.0, and it has committed the problem that the resources have not been released. In the Configuration. buildSessionFactory () function: the settings variable contains the object holding the connection pool. The connection object. If SessionFactoryImpl is created abnormally, conn will not be released. 2. In finally, return and throw are never used. If an exception is thrown or return is used, the exception that should be thrown will be lost. As shown below, it is intended that the Runtime exception should be thrown in f (), but the exception can no longer be caught in finnally with return. Copy the code static void f () {try {System. out. println ("here"); throw new RuntimeException ("my exception");} finally {return ;}} public static void main (String [] args) {f ();} copy code 3. If you want to call a method of an input parameter, you must perform a Null check. Or this information is required. If you do not perform a null check, the virtual machine will automatically throw the runtime NEP error. So many people don't care about it. If your method is called by someone else, and someone else cannot see your method code, the problem will be big. Copy the code static void f (String str) {System. out. println (str. length ();} public static void main (String [] args) {f (null);} copy the Code such as the code and display the thrown exception information, NPE occurs in row 9th of the f method. However, it is very likely that someone else has compiled the class when calling your code. In this case, it is difficult for callers to find problems. Therefore, you must perform an exception check and throw a new one with related prompts. The code of the open-source framework performs such a check. For example, a jdbcTemplate method checks the action through Assert. notNull. If it is null, a runtime exception is thrown. 4. Check for exceptions and non-check exceptions the Java exception structure is as follows: The RuntimeException and its subclass are not checked for exceptions. It does not force you to display and process data during programming. If an exception is fatal and cannot be recovered, and you do not know how to handle it in a way that captures the exception, or you do not have any benefit in capturing this exception, you should define this exception as a non-checked exception, it is handled by a dedicated exception handler at the top level. exceptions such as database connection errors, network connection errors, or file cannot be opened are generally non-checked exceptions. These exceptions are generally related to the external environment. Once they occur, they cannot be effectively handled. Spring Dao has chosen to convert all SQLException to DataAccessException, which is a runtime exception. In this way, the structure and readability of programming have been greatly improved. For example, if the database closes an exception, or even directly catch and record the related process, the exception is not thrown. For exceptions that can be avoided or can be recovered in the expectation and have corresponding handling methods, you can define such exceptions as check exceptions. For example, exceptions caused by illegal data input or business-related exceptions are basically inspection exceptions. When such exceptions occur, they can be effectively processed or restored to normal by retrying. 5. From the exception perspective, the user should not be exposed to Java exceptions, and the program should not crash without prompt. Java is widely used in the web field. Web containers such as Tomcat can handle exceptions very well. Generally, internal logic errors do not cause application crashes. The exception information is also displayed on the front-end page. During development or internal testing, the exception information should be directly exposed to the front-end, which facilitates reporting errors. During the official release phase, you should jump to a special page with errors such as 500. 6. When a catch exception occurs, the flushing throw exception should include the exception link exception chain, which is particularly critical for program debugging. The retention of the exception chain can be traced back to the abnormal source, which facilitates the correct and timely locating of exceptions. The loss of the exception chain is always fatal.

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.