Possible Duplicate:
Log runtime Exceptions in Java using log4j
I am developing a desktop application. I used Log4j to write log. How can I write log with NullPointerException
? I didn't predict that could happen.
Possible Duplicate:
Log runtime Exceptions in Java using log4j
I am developing a desktop application. I used Log4j to write log. How can I write log with NullPointerException
? I didn't predict that could happen.
If you mean just how to print the exception to the log, assuming the configuration is OK:
try {
....something
} catch(RuntimeException e) {
log.error("Got unexpected exception", e);
}
NullPointerException inherits from RuntimeExepction so you can safely catch it and any other runtime ones with the above code. The above code will NOT catch any exception which is inherit from Exception but not from RuntimeException.
If I understand your question properly, you do not want to put Try catch statements throughout your code to handle NullPointer Exception as it is not expected.
Simple way to handle is to put a null check before using the object reference for any operation. Also , place these null checks only on those objects where you can expect that it might not be initialized due to some other exception or error scenario.
i.e
if (objectReference!=null)
objectReference.CallSomeMethod();
Another example
String listofDefaulters =null;
String defaulters = getDefauter();
/**you might expect that you will always get defaulters from the method call but it might happen dat it can return null value also.
So always put a null check where you are not 100% sure if value will not be null**/
if (defaulters !=null)
defaulters.doSomeOperation();
If you want to do aspect oriented programming
, you may want to write an advice around Exception
including NullPointerException
and perform the logging e.g. below:
@Aspect
public class ExceptionLogging {
private static Logger log = null;
@Pointcut ("call(* *.*(..)))
public void exceptionLogMethods(){
}
@AfterThrowing(pointcut="exceptionLogMethods()", throwing="e")
public void handleException(Throwable ex, JoinPoint jointPoint) {
log = Logger.getLogger(jointPoint.getThis().getClass());
log.debug(jointPoint.getThis().getClass() + ex.getMessage());
}
}
You can use the class Preconditions
too in the Guava libraries for customize the exceptions and the messages.
The method Preconditions#checkNotNull(T, java.lang.Object)
throws a NullPointerException
if the reference T
is null
.
void method(String name) {
Preconditions.checkNotNull(name, "The name is null.");
// do something with the name
}
void otherMethod() {
try {
method("zerone"); // OK
method(null); // throws NPE
} catch(RuntimeExcetion e) {
LOG.error(e.getMessage(), e); // Message: "The name is null."
}
}