Sunday, 26 June 2016

What are the common Exception handling rules ?


Exception handling rules


#1. Prefer exceptions over Returning Error Codes
if (deletePage(page) == E_OK) {
   if (registry.deleteReference(page.name) == E_OK) {
     ....
   } else {
      .....
   }
} else {
   ....
}

try {
   deletePage(page);

   registry.deleteReference(page.name);
} catch (Exception e) {
    logger.log(e.getMessage());
}



#2. Extract Try/Catch Blocks
Example. More better than above - 1 method with core logic , other with try/catch block only
try {
   deletePageAndAllReferences(page);
} catch (Exception e) {
   logError(e);
}


private void deletePageAndAllReferences(Page page) throws Exception {….}


#3. Use Unchecked Exceptions
Checked exceptions :
  • increases error handling in many parts of our system
  • Breaking Encapsulation
So, Use checked exceptions only when :
  • If the caller knows & wants how to handle it
  • Dealing with Critical Systems or libraries

#4. Don’t Eat the Exception
try {
  ...
} catch (Exception ex) { }


try {
   ...
} catch (Exception ex) {
   ex.printStackTrace();
}



#5. Resist Temptation to write a Single Catchall
Single handler for many errors reduces the reliability of your program.

#6. Always use Catchall after handling known ones
You may not be sure that you handled all possible exceptions, so provide a default handler (catchall)

#7. Don’t Return NULL
Returning null needs its handling at all the places, which makes code awful.
Solution
  • Return a special case object
  • Wrap with another method that throws exception

#8. Don’t Pass NULL
Passing NULL should be handled inside the method or NullPointerException will be thrown
Unless the used API is passing NULL, you should avoid it.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.