Java Exceptions and log considerations

Source: Internet
Author: User
Tags finally block getmessage throw exception

First, unusual precautions

Simply sort out the following specification for exceptions:

1) in the exception handling module should provide accurate, easy-to-read error cause information.

2) do not handle exceptions that can be avoided.

3) A method should not throw too many types of exceptions, preferably no more than three.

4) Do not use the return statement inside the try and finally fields.

5) database, IO operations, etc. involving resource pool leaks must be in the finally to release resources.

6) Place the Try/catch segment outside the loop.

7) Do not use exceptions for program flow control, exception handling efficiency is lower than the conditional branch, and the jump process is difficult to predict.

8) The use of exception handling in the program or the use of error return code processing, based on whether the program structure is beneficial to determine, and the exception and error code should not be mixed, the recommended use of exceptions.

9) Exception capture try not to direct catch (Exception), the exception should be broken down processing.

10) For the exception should be classified processing, do not only capture exception.

11) cannot be ignored for exceptions and should be logged in.

Second, abnormal optimization

2.1, do not ignore checked Exception

1) Handle the exception and fix it so that the program continues execution. For example, when a database query is made, the database connection is broken and the link is successfully re-linked.

2) After analyzing the exception and discovering that it cannot be processed here, re-throw the exception and let the caller handle it. Exceptions are thrown up in order, and if all methods do not handle the exception properly, the user will be prompted in the appropriate way to determine the next steps. For example, in a database query, the broken chain after a few retries continue to fail.

3) If you convert the exception to another exception and then throw it, you should be careful not to lose the original exception information. This is typically used to encapsulate the underlying exception as an application-level exception.

4) Do not catch exceptions, you should use the throws declaration in the function definition to throw the exception and let the caller handle the exception.

5) Therefore, when capturing a checked exception, the exception must be handled, and if it is considered unnecessary to be handled here, do not catch the exception, declare the method in the method body throws an exception, and the upper-level caller handles the exception.

2.2. Do not capture unchecked Exception

There are two kinds of checked Exception:

1) Error: This is an unrecoverable failure of the JVM, such as a memory overflow, which cannot be processed.

2) RuntimeException: This condition is caused by the wrong encoding, after the exception of the need to modify the code to repair, generally after the catch is not properly handled, so should not be captured. (This rule does not apply to the daemon thread in handling catch runtime exception)

2.3. Do not capture all exceptions at once

1) For each type of exception thrown in a try block, it is likely that different processing and recovery measures are required, and because there is only one catch block, the processing cannot be implemented separately.

2) The try block may also throw RuntimeException, the code captures all the thrown runtimeexception without doing any processing, masking the programming errors that can cause the program to be difficult to debug.

2.4. Use the finally block to release resources

What is a resource: a limited number of objects used in a program, or an object that can only be accessed exclusively. For example: threads, thread pools, database connections, FTP connections, because resources are "limited", so resources must be freed after they are used to prevent resources in the program from being exhausted and affecting the program's operation. Some resources, when used, are automatically freed, such as threads, and some resources need to display releases, such as database connections.

The finally keyword guarantees that the statements in finally will execute regardless of whether the program leaves the try block in any way.

Therefore, when you need a place to execute code that must be executed under any circumstances, you can put the code in the finally block. When you use resources in your program, such as database connections, files, FTP connections, threads, etc., you must write code that demonstrates these resources to the finally block.

2.5. Cannot throw exception in finally block

The Java exception handling mechanism guarantees that the finally fast code is executed in all cases before leaving the entire try,catch,finally block. When an exception is thrown out of the Try,catch block, the Java Virtual machine first goes to the finally block to execute the code in finally, and then throws the exception. However, if an exception is thrown in the finally block, the exception of the Try,catch block cannot be thrown, the exception that is caught externally is the exception information in the finally block, and the real exception stack information that occurs in the Try,catch block is lost.

2.6. Bring the original exception information when throwing a custom exception

After the try block catches the thrown exception, a new custom exception is thrown to bring the stack information of the original exception, which facilitates the troubleshooting.

2.7. Do not use exception mechanisms and return values at the same time for exception handling

For example:

try{

......

}catch (Exception e) {

throw new Exception (msg,e);

Return "";

}

Mixed use of Java exception handling mechanisms and return values makes the exception handling part of the program "ugly" and difficult to understand. If there are many different exceptions, define a number of different exceptions instead of using exception and return values in the same way as the code above.

Third, log optimization and precautions

3.1. Log context

The information in the log must be brought into context as much as possible, comparing the following two log information, which is more useful than the former.

3.2, error or warn level encountered exception situation as far as possible log complete exception information

The error and warn levels are serious situations, meaning that the system is faulty or dangerous, and we need more information to help analyze the cause, and the more information is helpful at this time. Contains the following content:

1) When you're doing something, you're making a mistake.

2) What data do you use to make a mistake when doing this thing?

3) What is the error message?

Compare the following three log statements, the first one provides detailed information, the second one provides only partial information, the exception message does not necessarily contain useful information, the third only tells you the error, the others you do not know:

1) log.error ("Error obtaining user information of user [{}]", Username,ex);

2) Log.error ("Error obtaining user information for user [{}]", Username,ex.getmessage ());

3) Log.error ("Error obtaining user information for user [{}]");

3.3, the basic logger code

1) usually only one logger object is used in an object, logger should be static final, and private fianl should be used only if the few need to pass logger in the constructor.

Static final Logger Logger = Loggerfactory.getlogger (Main.class);

2) Output Exceptions all throwable information, because the Logger.error (msg) and Logger.error (Msg,e.getmessage ()) such as the log output method will lose the most important stacktrace information.

Void foo () {

try{

......

}catch (Exception e) {

Logger.error (E.getmessage ());//Error

Logger.error ("msg", E.getmessage ());//Error

Logger.error ("msg", E);//correct

}

}

3) for exceptions that are not particularly important, do not allow logging and then throw an exception, because the log is logged more than once, allowing only one record

try{

......

}catch (Exception ex) {

Logger.error (ERRORMESSAGE,EX);

Throw new Usersercviceexception (ERRORMESSAGE,EX);

}

4) system print (including SYSTEM.OUT.PRINTLN and SYSTEM.ERROR.PRINTLN) statements are not allowed.

5) E.printstacktrace is not allowed to appear.

6) Log Performance considerations, if the code is the core code, the execution frequency is very high, then the output log is recommended to increase the judgment, especially the low-level output <debug, info, warn>.

7) Meaningful logs

In general, some of the more meaningful status data is recorded in the program log: program start, Exit Time:

The running time of the program, the execution progress of the time-consuming program, and the state change of important variables.

In addition, in the public log to avoid the printing program debugging or prompt information.

Description: The output of invalid log is not conducive to the performance improvement of the system, and is not conducive to the rapid positioning of error points. Logging Please think: Are these logs really seen? What can you do to see this log? Can you benefit from troubleshooting?

Java Exceptions and log considerations

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.