0

可能重复:
使用 log4j 在 Java 中记录运行时异常

我正在开发一个桌面应用程序。我用 Log4j 写日志。我怎样才能写日志NullPointerException?我没有预料到会发生这种情况。

4

4 回答 4

1

如果您的意思是如何将异常打印到日志中,假设配置正常:

try {
     ....something
} catch(RuntimeException e) {
     log.error("Got unexpected exception", e);
}

NullPointerException 继承自 RuntimeExepction,因此您可以使用上述代码安全地捕获它和任何其他运行时异常。上面的代码不会捕获任何继承自 Exception 但不是从 RuntimeException 继承的异常。

于 2012-10-31T02:18:25.960 回答
1

如果我正确理解您的问题,您不想在整个代码中放置 Try catch 语句来处理 NullPointer 异常,因为它不是预期的。

处理的简单方法是在将对象引用用于任何操作之前进行空检查。此外,仅将这些空检查放在那些您可以预期它可能由于某些其他异常或错误情况而无法初始化的对象上。

IE

if (objectReference!=null)
           objectReference.CallSomeMethod();

另一个例子

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();
于 2012-10-31T02:18:46.450 回答
0

如果你想做aspect oriented programming,你可能想写一个建议,Exception包括NullPointerException并执行下面的日志记录:

 @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());
   }
  }
于 2012-10-31T02:25:27.360 回答
0

Preconditions您也可以在Guava 库中使用该类来自定义异常和消息。

如果引用是,则该方法Preconditions#checkNotNull(T, java.lang.Object)抛出 a 。NullPointerExceptionTnull

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."
    }
}
于 2012-10-31T02:32:03.790 回答