我发现下面的异常处理代码可以处理应用程序抛出的所有异常,包括运行时。
public static void handleException(String strMethodName,
Exception ex) throws CustomException{
String strMessage = "";
try {
throw ex;
}
catch (NullPointerException npe){
logger.log(pr, strMethodName, npe.getMessage());
strMessage=ERR_02;
throw new CustomException(strMessage);
}
catch(IndexOutOfBoundsException iobe) {
logger.logMethodException(strMethodName,iobe.getMessage());
strMessage=ERR_03;
throw new CustomException(strMessage);
}
... So On
}
以下是我认为的一些缺点:
- 为了确定异常的根本原因,我们需要始终检查消息字符串。
- 不区分异常类型
优点:
- 更少的代码。 (代码可以最小化)
您能否告诉我是否应该采用这种机制。
最佳答案
不确定您使用该代码的情况。
在您的方法中,您不会重新抛出可用于调试的异常对象
public static void handleException(String strMethodName,
Throwable th){
String strMessage = "";
try {
throw th;
}
catch (Throwable thr){
logger.log(pr, strMethodName, npe.getMessage());
//get the appropriate error code from a method
strMessage=getErrorCode();
throw new CustomException(strMessage, th);
//CustomException is of type RuntimeException
}
}
通过捕获并“抛出”Throwable 对象,您可以确保即使是错误也能得到正确处理。 [重要的是不要抑制 Throwable 对象]
关于java - 通用异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16213063/