In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article will explain in detail the skills of Java exception handling for you. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.
The nine techniques for Java exception handling are:
1. Use exception 2 only in abnormal cases. Use check exceptions for recoverable conditions and run-time exception 3 for programming errors. Avoid unnecessary use of detected anomalies 4. It is in favor of using standard exception 5. Throw an exception that is suitable for abstraction 6. Record all exceptions thrown by each method. Include fault capture information in the detailed message 8. Strive for fault atomicity 9. Don't ignore exception 1. Use exceptions only in exception cases
The main purpose of this item is to avoid using exceptions for normal control flows.
For example, instead of using exceptions to terminate the loop control flow:
Try {Iterator iter =...; while (true) {Foo foo = i.next ();...} catch (NoSuchElementException e) {}
Regular iterations of the collection should be used:
For (Iterator iter =...; i.hasNext ();) {Foo foo = i.next ();...}
I didn't find any examples of using regular control flow exceptions.
two。 Use check exceptions for recoverable conditions and run-time exceptions for programming errors
In most cases, if the caller can recover the exception, you should use the checked exception. If not, run-time exceptions should be used. Run-time exceptions represent programming errors that can be prevented by checking certain prerequisites, such as array boundaries and nullability checks.
In the following method, IllegalArgumentException is a RuntimeException, which is used to indicate a programming error. Programming errors can usually be avoided by checking prerequisites. So this is a bad example based on this technique. You can avoid exceptions by checking the prerequisites, that is, the "hasNext ()" method here.
/ * Convert a tag string into a tag map. * * @ param tagString a space-delimited string of key-value pairs. For example, {@ code "key1=value1 key_n=value_n"} * @ return a tag {@ link Map} * @ throws IllegalArgumentException if the tag string is corrupted. * / public static Map parseTags (final String tagString) throws IllegalArgumentException {/ / delimit by whitespace or'= 'Scanner scanner = new Scanner (tagString) .useDelimiter ("\\ s + | ="); Map tagMap = new HashMap (); try {while (scanner.hasNext ()) {String tagName = scanner.next (); String tagValue = scanner.next (); tagMap.put (tagName, tagValue) } catch (NoSuchElementException e) {/ / The tag string is corrupted. Throw new IllegalArgumentException ("Invalid tag string'" + tagString + "');} finally {scanner.close ();} return tagMap;} 3. Avoid unnecessary use of detected anomalies
Checking for exceptions forces the caller to handle the exception, because if not, the compiler complains. Overuse of checking for exceptions puts a burden on the caller to handle the exception. So the checked exception should be used if necessary. The rule of thumb for using checked exceptions is that when exceptions cannot be avoided by checking prerequisites, callers can take some useful actions to handle exceptions.
The common run-time exception itself is an example of not overusing to check for exceptions. Common runtime exceptions are: ArithmeticException,ClassCastException exception, thrown: IllegalArgumentException,IllegalStateException exception, IndexOutOfBoundExceptions,NoSuchElementException exception, and NullPointerException exception.
In the following method, when propertyName is not one of the target cases, there is not much the caller can do, so a runtime exception is thrown.
@ Overridepublic Object get (String propertyName) {switch (propertyName.hashCode ()) {case 842855857: / / marketDataName return marketDataName; case-1169106440: / / parameterMetadata return parameterMetadata; case 106006350: / / order return order; case 575402001: / / currency return currency; case 564403871: / / sensitivity return sensitivity; default: throw new NoSuchElementException ("Unknown property:" + propertyName);} 4. In favor of using standard exceptions
The most frequently reused Java exception classes are as follows:
1.java.io.IO exception 2.java.io.FileNotFoundException3.java.io.UnsupportedEncodingException4. Java.lang.reflect.InvocationTargetException5.java.security.NoSuchAlgorithmException6.java.net.MalformedURLException7.java.text.ParseException8. Java.net.URISyntaxException9. Java.util.concurrent.ExecutionException10. Java.net.UnknownHostException
None of the top 10 is the most commonly used in the book. Note, however, that these are calculated by project, that is, if a class is used in a project, it is calculated only once, no matter how many methods are using it in the project. So this is calculated by the number of items, but by the number of times it appears in the code.
5. Throw an exception suitable for abstraction
The exception thrown should be related to the task performed by the caller. This article describes exception conversion (catching an exception and throwing another) and exception chain (wrapping an exception in a new exception to preserve the causal chain of the exception).
Private void serializeBillingDetails (BillingResult billingResult, BillingDetailsType billingDetails) {try {final JAXBContext context = JAXBContext .newInstance (BillingdataType.class); final ByteArrayOutputStream out = new ByteArrayOutputStream (); final Marshaller marshaller = context.createMarshaller (); marshaller.setProperty ("jaxb.formatted.output", Boolean.FALSE); final BillingdataType billingdataType = new BillingdataType (); billingdataType.getBillingDetails () .add (billingDetails) Marshaller.marshal (factory.createBillingdata (billingdataType), out); final String xml = new String (out.toByteArray (), "UTF-8"); billingResult.setResultXML (xml.substring (xml.indexOf (") + 13, xml.indexOf (")). Trim (); billingResult.setGrossAmount (billingDetails.getOverallCosts () .getGrossAmount ()) BillingResult.setNetAmount (billingDetails.getOverallCosts (). GetNetAmount ());} catch (JAXBException | UnsupportedEncodingException ex) {throw new BillingRunFailed (ex);}}
The above method catches JAXBException and UnsupportedEncodingException and rethrows a new exception appropriate to the level of method abstraction. The new BillingRunFailed exception wraps the original exception. So this is a good example of an anomaly chain. The advantage of exception chains is that they retain low-level exceptions that help debug problems.
6. Record all exceptions thrown by each method
This is a serious underuse. Most public API do not have an @ throws Java document to explain the exception thrown.
This is a good example.
... * * @ throws MalformedURLException The formal system identifier of a * subordinate catalog cannot be turned into a valid URL. * @ throws IOException Error reading subordinate catalog file. * / public String resolveSystem (String systemId) throws MalformedURLException, IOException {...
This is a bad example of a lack of information about when an exception is thrown.
* @ throws Exception exception * / public void startServer () throws Exception {if (! externalDatabaseHost) {7. Include fault capture information private OutputStream openOutputStream (File file) throws IOException {if (file.exists ()) {if (file.isDirectory ()) {throw new IOException ("File'" + file + "'exists but is a directory");} if (! file.canWrite ()) {throw new IOException ("File'" + file + "'cannot be written to") in the detailed message }} else {final File parent = file.getParentFile (); if (parent! = null) {if (! parent.mkdirs () & &! parent.isDirectory ()) {throw new IOException ("Directory'" + parent + "'could not be created");}} return new FileOutputStream (file, false);}
In this method, IOException uses different strings to pass different fault capture information.
8. Strive for fault atomicity
Item 8 is about failure. The general rule is that failed methods should not change the state of objects in the method. In order to fail as soon as possible, one way is to check the validity of the parameters before performing the operation. The following is a good example of following this tip.
/ * Assigns a new int value to location index of the buffer instance. * @ param index int * @ param newValue int * / public void modifyEntry (int index, int newValue) {if (index)
< 0 || index >Size-1) {throw new IndexOutOfBoundsException ();} / ((int []) bufferArrayList.get ((int) (index / pageSize) [index% pageSize] = ((int []) bufferArrayList.get ((index > > exp) [index & r] = newValue;} 9. Do not ignore the exception public static Bundle decodeUrl (String s) {Bundle params = new Bundle (); if (s! = null) {String array [] = s.split ("&"); for (String parameter: array) {String v [] = parameter.split ("=") Try {params.putString (URLDecoder.decode (v [0], "UTF-8"), URLDecoder.decode (v [1], "UTF-8"));} catch (UnsupportedEncodingException e) {e.printStackTrace ();} return params;}
Printing stack traces should almost always be avoided in production code. This is as bad as ignoring exceptions. This will write to the standard error stream, which is not where logging uses the logging framework.
This is the end of this article on "what are the skills of Java exception handling". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.
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.