Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

10 hands-on experiences in resolving Java anomalies


May 31, 2021 Article blog


Table of contents


This article is from the public number: Java Way, author Hollis

Exception handling plays an extremely important role in writing healthy and robust Java applications. E xception handling is not a functional requirement, in practice, exception handling is not only to know the syntax is so simple. Here are 10 best practices.

Don't use printStackTrace() for online code

Be sure to check that there is no printStackTrace() in the code after you have finished writing it. Because printStackTrace() only outputs incorrect stack information on the console, it is only suitable for code debugging.

You really need to log exceptions, use logging.

Never swallow an exception in a catch block

catch (NoSuchMethodException e) {
     return null;
  }

Never handle an exception, but return null, so that the exception will be swallowed, can not get any failure information, will bring great difficulties in troubleshooting future problems.

Declare a specific detected exception where it is needed

 public void foo() throws Exception { //错误做法
  }

Be sure to try to avoid the code above, because his caller has no idea what the cause of the error is.

In a method declaration, you can throw some specific detected exceptions by the method. If there are more than one, throw multiple separately, so that the user of this method can handle each exception specifically, thus avoiding failure.

public void foo() throws SpecificException1, SpecificException2 { 
//正确做法
}

Always catch only exceptions that can be handled

catch (NoSuchMethodException e) 
{
    throw e; //这代码一点用都没有
}

This is a basic concept, and when you can handle him, you catch the exception again, otherwise never catch him.

If you can't handle it in a catch block, it doesn't make any sense to capture it before throwing it directly.

Try to capture specific subclasses instead of directly capturing Exception classes

try {
      someMethod();
  }
  catch (Exception e) 
  {
      LOGGER.error("method has failed", e);
  }

The biggest problem with this code is that if the developer of someMethod() adds a specific exception to it, and expects the caller to be able to deal with him in particular.

But the caller catch the Exception class directly, resulting in never knowing the details of the change someMethod This can cause the program to crash at some point in time while running.

Never catch a Throwable class

This is a serious problem because Error in Java can also be a subclass of Throwable H owever, Error is beyond the control of the Java virtual machine itself. The Java virtual machine may not even request the user's catch clause in the event of any errors.

Always override the original exception in the custom exception so that the stack trace is not lost

 catch (NoSuchMethodException e) 
  {
  throw new MyServiceException("Some information: " + e.getMessage());  //错误做法
  }

The above command may lose the stack trace of the main exception. The correct approach is to:

catch (NoSuchMethodException e) {
     throw new MyServiceException("Some information: " , e);  //正确做法
}

Exceptions can be logged or thrown, but do not do so at the same time

catch (NoSuchMethodException e) {
     LOGGER.error("Some information", e);
     throw e;
  }

As the code above shows, throwing and logging can generate multiple log messages in the log file.

This can lead to the same problem, but there are many different error messages in the log, confusing the developer.

Never throw an exception in finally

try {
  someMethod();  //抛出 exceptionOne
}
 finally
{
  cleanUp();    //如果在这里再抛出一个异常,那么try中的exceptionOne将会丢失forever
}

In the example above, if someMethod() throws an exception, and in finally cleanUp() also throws an exception, the initial exceptionOne (the correct error exception) is lost forever.

If you do not intend to handle exceptions, use a finally block instead of a catch block

try {
  someMethod();
}
finally
{
  cleanUp();
}

This is also a good practice. I f you access another method in your method that throws an exception that you don't want to handle, but still needs to do some cleanup, clean up in the finally Do not use catch blocks.

These are the 10 practical experiences of W3Cschool编程狮 on solving Java anomalies, and I hope to help you.