Java Exception

Exception Hierarchyรูปภาพ

Catch multiple exception in Java 7

catch(IOException | SQLException | Exception ex){
    logger.error(ex);
    throw new MyException(ex.getMessage());
}

try-with-resource in Java 7

instead of finally close resource

try (MyResource mr = new MyResource()) {
    System.out.println("MyResource created in try-with-resources");
} catch (Exception e) {
    e.printStackTrace();
}

Error Code Example

MyException.java

package com.journaldev.exceptions;
public class MyException extends Exception {
    private static final long serialVersionUID = 4664456874499611218L;
    private String errorCode="Unknown_Exception";
    public MyException(String message, String errorCode){
        super(message);
        this.errorCode=errorCode;
    }
    public String getErrorCode(){
        return this.errorCode;
    }
}

CustomExceptionExample.java

package com.journaldev.exceptions;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public class CustomExceptionExample {
    public static void main(String[] args) throws MyException {
        try {
            processFile("file.txt");
        } catch (MyException e) {
            processErrorCodes(e);<
        }
    }
    private static void processErrorCodes(MyException e) throws MyException {
        switch(e.getErrorCode()){
             case "BAD_FILE_TYPE":
                   System.out.println("Bad File Type, notify user");
                   throw e;
             case "FILE_NOT_FOUND_EXCEPTION":
                   System.out.println("File Not Found, notify user");
                   throw e;
             case "FILE_CLOSE_EXCEPTION":
                   System.out.println("File Close failed, just log it.");
                   break;
             default:
                   System.out.println("Unknown exception occured, lets log it for further debugging."+e.getMessage());
                   e.printStackTrace();
         }
    }
    private static void processFile(String file) throws MyException {
        InputStream fis = null;
        try {
             fis = new FileInputStream(file);
        } catch (FileNotFoundException e) {
             throw new MyException(e.getMessage(),"FILE_NOT_FOUND_EXCEPTION");
        }finally{
             try {
                  if(fis !=null)fis.close();
             } catch (IOException e) {
                  throw new MyException(e.getMessage(),"FILE_CLOSE_EXCEPTION");
             }
        }
    }
}

Best practices

1. Throw Early

i.e. instead of

Exception in thread "main" java.lang.NullPointerException
at java.io.FileInputStream.&lt;init&gt;(FileInputStream.java:134)
at java.io.FileInputStream.&lt;init&gt;(FileInputStream.java:97)
at com.journaldev.exceptions.CustomExceptionExample.processFile(CustomExceptionExample.java:42)
at com.journaldev.exceptions.CustomExceptionExample.main(CustomExceptionExample.java:12)

do this

private static void processFile(String file) throws MyException {
     if(file == null) throw new MyException("File name can't be null", "NULL_FILE_NAME");
    //further processing
}

throw early, so we can easily identify the problem

com.journaldev.exceptions.MyException: File name can't be null
at com.journaldev.exceptions.CustomExceptionExample.processFile(CustomExceptionExample.java:37)
at com.journaldev.exceptions.CustomExceptionExample.main(CustomExceptionExample.java:12)

2. Catch Late

the cons of catching exception early

– caller program doesn’t get any notification for the exception

– other applications that might want to process exception in a different manner.

3. Using Custom Exceptions

It’s always better to define exception handling strategy at the design time and rather than throwing and catching multiple exceptions, we can create a custom exception with error code and caller program can handle these error codes. Its also a good idea to create a utility method to process different error codes and use it.

4. Use Exceptions Judiciously

Exceptions are costly and sometimes it’s not required to throw exception at all and we can return a boolean variable to the caller program to indicate whether an operation was successful or not.

For example, while updating the stock quotes in database from a third party webservice, we may want to avoid throwing exception if the connection fails.

5. Document the Exceptions Thrown

Use javadoc @throws to clearly specify the exceptions thrown by the method

full version is at javacodegeeks

javadoc troubleshooting

The below is some problem I faced when I due with javadoc. Therefore, I think it is good to  note it here.

Problem 1

C:\xxx\yyy.java:18: cannot access jxl.Cell
bad class file: C:\aaa\bbb\WEB-INF\lib\jxl.jar(jxl/Cell.class)
class file has wrong version 50.0, should be 49.0
Please remove or make sure it appears in the correct subdirectory of the classpath.
import jxl.Cell;

Solution

Use the right “javadoc” version. In this case we should use javadoc of jdk 6 ( 50.0 ), in stead of jdk 5 ( 49.0 ).

Note that in eclipse, we can set the “Javadoc command” from the “Generate Javadoc” menu.
Use the right javadoc program from there.

Problem 2

and another problem is that some jars may not have the doc attached.

That may affects if we generate the doc from the code that use annotation from the jar that has no doc attached. ( this is related with ‘package-list’ issue ).

The solution is point the -linkoffline to the doc folder, i.e.

-linkoffline file:/D:/sss/ttt/uuudoc . com.wordpress.dsin.mypackagename

VM option for larger heap space

-J-Xmx1024m

Encoding for Another language

-encoding "Shift-JIS" -docencoding "UTF-8" -charset "UTF-8"