通用异常处理

时间:2013-04-25 11:04:13

标签: java exception-handling

我在下面找到了代码,用于处理应用程序(包括运行时)抛出的所有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
     }

以下是我认为的一些缺点:

  1. 要识别异常的根本原因,我们需要始终检查消息字符串。
  2. 没有异常类型的分离
  3. 优势:

    1. 更少的代码。 (代码可以最小化)
    2. 请告诉我是否应该采用这种机制。

1 个答案:

答案 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对象]