Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

  1. Never call methods that can be overridden by a subclass from the constructor.
    1. If you call any method from the constructor, either declare the whole class final.
    2. Or make method private, or final, or static.
  2. Exceptions Handling
    1. Checked Exceptions
      1. Handle checked exceptions when possible.
      2. In case the exception cannot be handled, allow it to propagate to the calling method by declaring "throws".
      3. If the method's API cannot be changed, wrap the original exception with WebApplicationException. Important! Never wrap unchecked exceptions with WebApplicationException!
      4. The InvocationTargetException should always be handled. Consider using the following pattern:
        Code Block
        
                try {
        
                } catch (InvocationTargetException e) {
                    Throwable targetException = e.getTargetException();
                    if (targetException instanceof RuntimeException) {
                        throw (RuntimeException) targetException;
                    }
                    throw new WebApplicationException(targetException);
                }
        
    2. Unchecked Exceptions (Runtime Exceptions)
      1. Don't catch unchecked exceptions unless you can handle them properly.
      2. Be aware of "catch (Exception e)" statement, since it also catches unchecked exception. If there are multiple checked exceptions that should be handled in the same way, consider using the following pattern:
        Code Block
        
        try {
            
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
           // handle exception here
        }
        

Logging

  1. In general logging is a good idea.
  2. Use Commons Logging.
  3. For debug messages, call if (log.isDebugEnabled()) prior to calling log.debug().
  4. The following code is usually bad. There is no need to log exception and re-throw it:
    Code Block
    try {
        
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        throw new RuntimeException(e);
    }
    
    Either log it, or re-throw.

...