我在下面找到了代码,用于处理应用程序(包括运行时)抛出的所有exec的异常处理。
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
}
以下是我认为的一些缺点:
优势:
请告诉我是否应该采用这种机制。
答案 0 :(得分:1)
不确定您使用代码的情况。
在您的方法中,您不会重新抛出可能用于调试的异常对象
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
}
}
通过捕获和“THROWING”Throwable对象,您确信即使错误也能正确处理。 [重要的是不要压制Throwable对象]