搜索            

无为论坛,没有版主,不删贴不封ID,北美中文论坛,加拿大中文论坛,红卫兵rolia,找工作,面试,职场,学英语,股市,炒股,心态,沟通

无为论坛,没有版主,不删贴不封ID,北美中文论坛,加拿大中文论坛,红卫兵rolia,找工作,面试,职场,学英语,股市,炒股,心态,沟通

Avatar

exception handling: good and bad practices (IT)

by super(学霸) ⌂, 2014-11-08 12:54

Recently the following piece of code tripped me. The root exception was completely swallowed so just by reading the log file I had no way of knowing where the error first occured. And I wasn’t able to run it locally in my Eclipse.

	
try {
   fieldValue = method.invoke(this);
}
catch (Exception ex) {
   // code below masks root Exceptions.
   logger.info(new StringBuilder().append("Exception while retrieving field: ")
      .append(fieldName.getValue())
      .append("::")
      .append(Arrays.toString(ex.getStackTrace())).toString());
   throw new RuntimeException(
      new StringBuilder().append(this.getClass().getName()).
         append("Error while processing field! : ").append(fieldName)
         .toString());
}

As code, this is bad, but as example, this is very good. I’d like to use it to discuss good and bad practices in Java exception handling.


Bad practice #1: excessive exception handling.

If the above code doesn’t catch the exception, the caller will get it, together with the complete exception chain, and of course the root exception. You might argue that the code at least highlighted the field which is failing. However, that piece of information should be already in the stack trace as the name of the method being invoked.

To handle exceptions every step of the way adds a lot of non-processing code which crowds out business logic and greatly reduces code readability. The above code contains only one line of business logic, the rest, 10 times of the volume, is about error handling which adds no value.

Excessive exception handling often causes same exception to be logged many times, each time with stack trace. This makes log files very difficult to navigate and makes debugging with log files nearly impossible.


Bad practice #2: swallow exceptions.

Most common way to swallow an exception is to catch it and log it as INFO. As a result, the stack trace is completely lost. The only way to figure out the bug is to reproduce it locally which is often time consuming and sometimes even impossible.

Surprisingly, this kind of code is very common.

	
logger.info("error happened while retrieving the field: "+ex.getMessage();

In the original example, the programmer is obviously aware of this pitfall so he printed out the stack trace even though he used logger.info(). Unfortunately, his code failed to print out root causes so the most important information was still swallowed.


Bad practice #3: throw a new exception with or without the original exception.

Very often it’s enough to just throw the original exception. Wrapping it with another exception adds little value. It not only causes confusion to downstream classes, it also makes exception handling more burdensome to the programmer so he is more likely to cut corners, such as to throw a new exception without wrapping the old, or to not do anything at all.


Now the good practices:

Good practice #1: Do not handle exceptions. Let them bubble up to the highest possible caller. This greatly reduces the volume of exception handling code and makes the code a lot more readable and maintainable. And most importantly, the stack traces are not tainted by incorrect handling of exceptions.

Good practice #2: Do print out stack traces for programming errors. Stack traces are important for unexpected programming errors because we otherwise would have no way of knowing exact which line caused the error.

Good practice #3: Do not print out stack traces for business exceptions, like “account not found”. Business exceptions happen at known points in the code and the stack traces are available with just a couple of mouse clicks in Eclipse. Stack traces tend to make log files very difficult to understand: it’s easy to miss important information and very easy to confuse one thing for another. Printing out stack traces for business exceptions unnecessarily adds to the mess.

---
serve the people

  667 views

整个话题:

 RSS Feed of thread

 
[x]