Wednesday, February 6, 2013

Handling Interrupted Exception (Good Coding Practices)


Never swallow interrupted exception.

Always either re-throw the exception (or) call Thread.currentThread().interrupt() which sets a flag that this thread has been interrupted, perform any cleaning tasks and make use of this flag to take the appropriate action by checking Thread.currentThread().isInterrupted()

The last thing to do will be to swallow the Exception.

Note: Thread.currentThread().interrupt() doesn't actually throw an interrupted exception, but sets a flag that indicates this thread has been interrupted by other application.

Reference: http://www.ibm.com/developerworks/java/library/j-jtp05236/index.html


Creating a temporary file (to be deleted after immediate use) {good coding practices}

Creating a temporary file (to be deleted after immediate use) {good coding practices}

File f = null;
try {
    f = createNewFile();
    // do your stuff here.
}
catch (Exception e) {

}
finally {
     if( f != null ) {
         f.delete();
     }
}

This way, we always ensure that file is deleted before use. and any return statements within try{} block will still doesn't prevent file from deleting.