In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-07 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
In this issue, the editor will bring you about the exception handling methods in Java. The article is rich in content and analyzed and described from a professional point of view. I hope you can get something after reading this article.
What is an anomaly?
The English word of exception is exception. Exception is essentially a program error, including program logic error and system error. Such as the use of empty references, array subscript crossing bounds, memory overflow errors, and so on, these are unexpected situations that deviate from the intention of our program itself. Errors often occur in the process of writing a program, including errors during compilation and running. Errors that occur during compilation are corrected by the compiler, but run-time errors are beyond the compiler's power. and run-time errors are often unpredictable. If an error occurs while the program is running, if ignored, the program will terminate or directly cause the system to crash, which is obviously not the result we want to see.
How to deal with and remedy the errors that occur during the operation? Java provides an exception mechanism for handling, through the exception mechanism to handle errors that occur during the run of the program. Through the exception mechanism, we can better improve the robustness of the program.
Anomaly classification
Java treats exceptions as objects and defines a base class, java.lang.Throwable, as the superclass of all exceptions.
Java includes three types of exceptions: inspecting exceptions (checked exceptions), non-inspecting exceptions (unchecked Exceptions), and errors (errors).
Checked exceptions are exceptions that must be declared in the throws clause of a method. They extend the exception and are designed to be a type of exception "in front of you". JAVA wants you to be able to deal with them because they depend in some way on external factors outside the program. The checked exception indicates expected problems that may occur during normal system operation. These exceptions usually occur when you try to use an external system over a network or file system. In most cases, the correct response to an inspecting exception should be to try again later, or to prompt the user to modify its input.
Non-inspecting exceptions (unchecked Exceptions) are exceptions that do not need to be declared in the throws clause. Due to program errors, JVM does not force you to deal with them, because most of them are generated at run time. They extend RuntimeException. The most common example is NullPointerException, where unchecked exceptions may not be retried, and the right thing to do is to do nothing and let it out of your method and execution stack.
Errors (errors) are serious runtime environment problems and are certainly irrecoverable. OutOfMemoryError,LinkageError and StackOverflowError, for example, usually cause programs to crash.
All exceptions that are not Runtime Exception are collectively referred to as Checked Exception, also known as checked exceptions. The occurrence of such anomalies is not the problem of the program itself, but is usually caused by external factors. In order to prevent the program from interrupting or getting incorrect results when these exceptions occur, Java requires that when writing program code that may produce such exceptions, you must do exception handling.
The Java language refers to all exceptions derived from the RuntimeException class or the Error class as non-inspecting exceptions.
The Java exception hierarchy diagram is shown in the following figure:
Now that we understand the basic concepts and classification of exceptions, let's explore the best practices for exception handling.
Best practices for exception handling do not ignore the caught exception catch (NoSuchMethodException e) {return null;}
Although an exception is caught, nothing is done, and unless you are sure that the exception can be ignored, you should not do so. This will cause the outside world not to know that an error has occurred in the method and to determine the cause of the location error.
Throw a specific check exception public void foo () throws Exception {/ / error mode} in your method
Be sure to avoid the above code example, which undermines the purpose of checking exceptions. Declare specific checking exceptions that your method may throw, and if there are only too many such checking exceptions, you should wrap them in your own exceptions and add information to the exception message. If possible, you can also consider code refactoring.
Public void foo () throws SpecificException1, SpecificException2 {/ / correct mode} capture specific subclasses instead of Exception classes try {someMethod ();} catch (Exception e) {/ / incorrect mode LOGGER.error ("method has failed", e);}
The problem with catching exceptions is that if the method called later adds a new checking exception to its method declaration, the developer's intention is to handle the specific new exception. If your code just catches an exception (or Throwable), you will never know the change, and your code is now wrong and may break at any time at run time.
Never capture the Throwable class
This is a more serious problem because Java Error is also a subclass of Throwable, Error is an irreversible condition that JVM itself cannot handle, and for some JVM implementations, JVM may not even actually call the catch clause on Error.
Always correctly wrap the exception in the custom exception so that the stack trace does not lose catch (NoSuchMethodException e) {throw new MyServiceException ("Some information:" + e.getMessage ()); / / error mode}
This breaks the stack trace of the original exception and is always wrong, and the right thing to do is:
Catch (NoSuchMethodException e) {throw new MyServiceException ("Some information:", e); / / correct way} either log or throw an exception, but do not execute catch (NoSuchMethodException e) {/ / wrong mode LOGGER.error ("Some information", e); throw e;}
As in the code above, logging and throwing exceptions results in multiple log messages in the log file, has a single problem in the code, and is unfriendly to colleagues who try to analyze the log.
Never throw any exception in the finally block try {someMethod (); / / Throws exceptionOne} finally {cleanUp (); / / if finally still throws an exception, then exceptionOne will be lost forever}
As long as cleanUp () never throws any exceptions, the above code is fine, but if someMethod () throws an exception and cleanUp () throws another exception in the finally block, the program will only throw the second exception, and the original first exception (for the right reason) will be lost forever. If the code called in the finally block may throw an exception, be sure to either handle it or document it. Never let it be thrown out of the finally block.
Always catch only the actual handyable exception catch (NoSuchMethodException e) {throw e; / / avoid this situation because it does not help}
This is the most important concept, do not catch an exception for the sake of catching an exception, catch an exception only when you want to handle an exception, or want to provide other contextual information in the exception. If you can't handle it in a catch block, the best advice is not to capture it just to re-throw it.
Do not use printStackTrace () statements or similar methods
After you finish the code, don't ignore printStackTrace (), someone else may end up with these stacks, and there's no way to deal with it at all, because it doesn't attach any contextual information.
For exceptions that are not intended to be handled, directly use finallytry {someMethod (); / / Method 2} finally {cleanUp (); / / do cleanup here}
This is a good practice if you are accessing Method 2 in your method and Method 2 throws some exceptions that you do not want to handle in Method 1, but still want to do some cleaning when an exception occurs, and then clean up in the finally block instead of using the catch block.
Remember the principle of early throw and late catch
This is probably the most famous principle about exception handling. To put it simply, you should throw the exception as soon as possible and catch it as late as possible. You should wait until there is enough information to handle it properly.
This principle implies that you will be more likely to put it in a low-level method, where you will check whether a single value is empty or inappropriate. And you will raise the exception stack trace several levels until it reaches a sufficient level of abstraction to deal with the problem.
Clean up resources after exception handling
If you are using resources such as database connections or network connections, be sure to clear them. If the API you are calling uses only non-checking exceptions, you should still use try-finally blocks to clean up resources. Access the resource in the try module, and finally close the resource in finally. Even if any exception occurs when accessing the resource, the resource closes gracefully.
Only exceptions related to the method are thrown
Correlation is important to keep your application clean. A method of trying to read a file that, if NullPointerException is thrown, does not give the user any relevant information. On the contrary, it would be better if the exception was wrapped in a custom exception. NoSuchFileFoundException is more useful to users of this method.
Do not use exceptions in the program for process control
Do not use exceptions to handle application logic in a project. Never do this, it will make the code difficult to read and understand.
Validate user input early to catch exceptions early in request processing
Always validate user input at a very early stage, and even before reaching controller, it will help you minimize the amount of exception handling code in your core application logic. If there is an error in user input, it can also be guaranteed to be consistent with the application.
For example, if you are in a user registration application, follow the following logic:
Authenticate user
Insert user
Verify address
Insert address
If something goes wrong, roll back everything.
This is incorrect, it will put the database in an inconsistent state in various situations, and you should first validate everything, and then put the user data in the dao tier and update the database. The right thing to do is:
Authenticate user
Verify address
Insert user
Insert address
If the problem rolls back,
An exception can only be contained in one log LOGGER.debug ("Using cache sector A"); LOGGER.debug ("Using retry sector B")
Do not do this as above, using multi-line log messages for multiple LOGGER.debug () calls may look good in your test case, but when it is displayed in the log file of an application server with 100 threads running in parallel, all the information is output to the same log file, even if they are before and after in the actual code However, the two log messages may be separated by more than 100 lines in the log file. This should be done:
LOGGER.debug ("Using cache sector A, using retry sector B"); pass all relevant information to the exception as much as possible
Useful exception messages and stack traces are very important, and what's the use of logging if your log can't locate the exception?
Terminate the interrupted thread while (true) {try {Thread.sleep (100000);} catch (InterruptedException e) {} / / Don't do this doSomethingCool ();}
The InterruptedException exception indicates that you should stop what the program is doing, such as a transaction timeout or thread pool being closed.
Instead of ignoring InterruptedException, you should try your best to do what you are doing and complete the currently executing thread. The modified procedure is as follows:
While (true) {try {Thread.sleep (100000);} catch (InterruptedException e) {break;}} doSomethingCool (); for duplicate try-catch, use the template method
There are many similar catch blocks in the code that are useless and will only increase the repetition of the code, and you can use the template method to solve this problem.
For example, exception handling when trying to close a database connection.
Class DBUtil {public static void closeConnection (Connection conn) {try {conn.close ();} catch (Exception ex) {/ / Log Exception-Cannot close connection}
This type of approach will be used in many parts of the application. Instead of leaving this code everywhere, define the method above, and then use it like this:
Public void dataAccessCode () {Connection conn = null; try {conn = getConnection ();.... } finally {DBUtil.closeConnection (conn);}} use JavaDoc to log all exceptions in the application
It is a habit to use JavaDoc to record all exceptions that may be thrown by the runtime, including actions that users should follow as far as possible to prevent them from happening.
The above is the Java shared by the editor and those exception handling methods. If you happen to have similar doubts, please refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.