In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-04 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)06/01 Report--
Java to deal with Exception's nine best practices are, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain for you in detail, people with this need can come to learn, I hope you can gain something.
Handling exceptions in Java is not an easy task. Not only is it difficult for beginners to understand, but even some experienced developers need to spend a lot of time thinking about how to handle exceptions, including which exceptions need to be handled, how to handle them, and so on. This is why most development teams make rules to regulate the handling of exceptions. These specifications between teams are often very different.
1. Clean up resources in Finally blocks or use try-with-resource statements
When using a resource like InputStream that needs to be closed after use, a common mistake is to close the resource at the end of the try block.
Public void doNotCloseResourceInTry () {
FileInputStream inputStream = null
Try {
File file = new File (". / tmp.txt")
InputStream = new FileInputStream (file)
/ / use the inputStream to read a file
/ / do NOT do this
InputStream.close ()
} catch (FileNotFoundException e) {
Log.error (e)
} catch (IOException e) {
Log.error (e)
}
}
There is no problem with the above code running without any exception. But when a statement in a try block throws an exception or self-implemented code throws an exception, the final close statement is not executed and resources cannot be released.
It makes sense to put all the cleaned code in a finally block or use a try-with-resource statement.
Public void closeResourceInFinally () {
FileInputStream inputStream = null
Try {
File file = new File (". / tmp.txt")
InputStream = new FileInputStream (file)
/ / use the inputStream to read a file
} catch (FileNotFoundException e) {
Log.error (e)
} finally {
If (inputStream! = null) {
Try {
InputStream.close ()
} catch (IOException e) {
Log.error (e)
}
}
}
}
Public void automaticallyCloseResource () {
File file = new File (". / tmp.txt")
Try (FileInputStream inputStream = new FileInputStream (file);) {
/ / use the inputStream to read a file
} catch (FileNotFoundException e) {
Log.error (e)
} catch (IOException e) {
Log.error (e)
}
}
two。 Specify a specific exception
Use the most specific exceptions to declare the method as much as possible to make the code easier to understand.
Public void doNotDoThis () throws Exception {
...
}
Public void doThis () throws NumberFormatException {
...
}
As mentioned above, NumberFormatException can literally see that it is a digital formatting error.
3. Document the exception
Documentation is also required when declaring that an exception is thrown on a method. As with the previous point, it is designed to provide as much information as possible to the caller so that exceptions can be better avoided / handled. This article is also recommended for 10 best practices for exception handling.
Add a throws declaration to the Javadoc and describe the scenario in which an exception is thrown.
/ * *
* This method does something extremely useful...
*
* @ param input
* @ throws MyBusinessException if... Happens
, /
Public void doSomething (String input) throws MyBusinessException {
...
}
4. Contains description information when throwing an exception
When throwing an exception, it is necessary to describe the problem and related information as accurately as possible, so that it can be read more easily, whether it is printed to the log or in the monitoring tool. thus, we can better locate the specific error information, the severity of the error, and so on.
But this is not to talk at length about the error message, because the original class name of Exception can reflect the cause of the error, so you only need to describe it in one or two sentences.
Try {
New Long ("xyz")
} catch (NumberFormatException e) {
Log.error (e)
}
NumberFormatException tells you that the exception is a formatting error and that additional information about the exception only needs to be provided with the error string. When the name of the exception is not obvious enough, you need to provide as much specific error information as possible.
5. First catch the most specific exception
Many IDE now intelligently prompt this best practice, prompting unreachable code when you try to catch the most general exception first. When there are multiple catch blocks, only the first matched catch block can be executed in capture order. Therefore, if you capture the IllegalArgumentException first, you cannot run to the capture of the NumberFormatException.
Public void catchMostSpecificExceptionFirst () {
Try {
DoSomething ("A message")
} catch (NumberFormatException e) {
Log.error (e)
} catch (IllegalArgumentException e) {
Log.error (e)
}
}
6. Do not capture Throwable
Throwable is the parent class of all exceptions and errors. You can capture it in a catch statement, but never do that. If catch has throwable, not only all exception will be captured, but also error will be captured. Error is a jvm error that indicates that it is unrecoverable. So do not capture error unless you are absolutely sure that you can handle it or are required to do so.
Public void doNotCatchThrowable () {
Try {
/ / do something
} catch (Throwable t) {
/ / don't do this!
}
}
7. Don't ignore exceptions
In many cases, developers are confident that they won't throw exceptions, so they write a catch block without doing any processing or logging.
Public void doNotIgnoreExceptions () {
Try {
/ / do something
} catch (NumberFormatException e) {
/ / this will never happen
}
}
But the reality is that unexpected exceptions often occur or it is impossible to determine whether the code here will be changed in the future (removing the code that prevents the exception from being thrown), and at this time, because the exception is caught, it is impossible to get enough error information to locate the problem. It makes sense to at least record abnormal information.
Public void logAnException () {
Try {
/ / do something
} catch (NumberFormatException e) {
Log.error ("This should never happen:" + e)
}
}
8. Do not record and throw an exception
You can find that a lot of code and even class libraries have logic to catch exceptions, log them, and throw them again. As follows:
Try {
New Long ("xyz")
} catch (NumberFormatException e) {
Log.error (e)
Throw e
}
This processing logic seems reasonable. But this often outputs multiple logs to the same exception. As follows:
ERROR TestExceptionHandling:65-java.lang.NumberFormatException: For input string: "xyz"
Exception in thread "main" java.lang.NumberFormatException: For input string: "xyz"
At java.lang.NumberFormatException.forInputString (NumberFormatException.java:65)
At java.lang.Long.parseLong (Long.java:589)
At java.lang.Long. (Long.java:965)
At com.stackify.example.TestExceptionHandling.logAndThrowException (TestExceptionHandling.java:63)
At com.stackify.example.TestExceptionHandling.main (TestExceptionHandling.java:58)
As shown above, there is no more useful information attached to later logs. If you want to provide more useful information, you can wrap the exception as a custom exception.
Public void wrapException (String input) throws MyBusinessException {
Try {
/ / do something
} catch (NumberFormatException e) {
Throw new MyBusinessException ("A message that describes the error." e)
}
}
Therefore, catch the exception only when you want to handle it, otherwise you just need to declare it in the method signature and let the caller handle it.
9. Do not discard the original exception when you wrap the exception
It is a common practice to catch standard exceptions and wrap them as custom exceptions. In this way, more specific exception information can be added and exception handling can be done for it.
It is important to note that when wrapping exceptions, be sure to set the original exception to cause (Exception has constructors that can be passed into cause). Otherwise, losing the original abnormal information will make it difficult to analyze the error.
Public void wrapException (String input) throws MyBusinessException {
Try {
/ / do something
} catch (NumberFormatException e) {
Throw new MyBusinessException ("A message that describes the error." e)
}
}
To sum up, there are many different things to consider when throwing or catching exceptions. Many of these points are intended to improve the readability of the code or the usability of the api. Exceptions are not only an error control mechanism, but also a medium of communication, so discussing these best practices and developing specifications with your collaborators allows everyone to understand the relevant common concepts and be able to use them in the same way. Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.
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.