【问题标题】:Counting the Exception and Logging it in the same method [duplicate]计算异常并以相同的方法记录它[重复]
【发布时间】:2013-03-01 16:48:51
【问题描述】:

我正在查看count 发生的exceptions 的数量,并同时记录那些exceptions。所以我所做的是,我创建了一个方法addException,我在其中计算所有异常。

addException 方法将接受两个参数,one is the String,另一个是boolean flag,表示我们是否要因为任何异常而终止程序。意思是,如果该标志为真,那么只要有任何异常,我都需要终止程序。

因此,如果您查看我下面的 catch 块,我有 addException 方法调用来计算异常,并且在该方法调用下面我也在记录异常。

catch (ClassNotFoundException e) {
    addException(e.getCause() != null ? e.getCause().toString() : e.toString(), Read.flagTerminate);
    LOG.error("Threw a ClassNotFoundException in " + getClass().getSimpleName(), e);
} catch (SQLException e) {
    addException(e.getCause() != null ? e.getCause().toString() : e.toString(), Read.flagTerminate);
    //DAMN! I'm not....
    LOG.error("Threw a SQLException while making connection to database in " + getClass().getSimpleName(), e);
}


/**
 * A simple method that will add the count of exceptions and name of
 * exception to a map
 * 
 * @param cause
 * @param flagTerminate 
 */
private static void addException(String cause, boolean flagTerminate) {
    AtomicInteger count = exceptionMap.get(cause);
    if (count == null) {
        count = new AtomicInteger();
        AtomicInteger curCount = exceptionMap.putIfAbsent(cause, count);
        if (curCount != null) {
            count = curCount;
        }
    }
    count.incrementAndGet();

    if(flagTerminate) {
        System.exit(1);
    }
}

问题陈述:-

现在我要找的是-

有没有更简洁的方法来做同样的事情?这意味着现在我正在计算方法中的异常,然后在 catch 块内的下一行打印出异常。

是否可以在同一个addException 方法中完成这两件事?如果该标志为真以终止程序,则也以适当的日志记录终止程序。

重写addException method 的最佳方法是什么? 感谢您的帮助。

【问题讨论】:

  • 这与您的其他问题有何不同 - stackoverflow.com/questions/14783266/…
  • 我们正在做同一个项目。我不知道他已经发布了。对于那个很抱歉。那么有什么办法可以消除这个问题呢?他给了我描述并请我帮忙。
  • 您可以删除此问题,并使用所需的任何详细信息更新另一个问题。我假设你们都在共享一个帐户?

标签: java exception try-catch


【解决方案1】:

有没有更简洁的方法来做同样的事情?正确的意思 现在我正在计算方法中的异常,然后打印出 catch 块内的下一行中的异常。

是否可以在同一个 addException 中做这两件事 方法?如果标志为真终止程序,则 使用正确的日志记录终止程序。

是的,如果您愿意,您可以传递异常本身和标志,而不是将 String 原因传递给 addException 方法。甚至可以在 addException 方法中进行完整的捕获,例如:

catch (ClassNotFoundException|SQLException e) {
    addException(e, Read.flagTerminate);
} 

catch (Exception e) {
    addException(e, Read.flagTerminate);
}

甚至:

catch (ClassNotFoundException e) {
    addException(e, Read.flagTerminate, "Threw a ClassNotFoundException in "); //An the addException method logs the message passed.    
} catch (SQLException e) {
    addException(e, Read.flagTerminate, "Threw a SQLException while making connection to database in ");
}

您可以在类中有一个映射,该映射存储了哪些异常应该停止执行,哪些不应该停止,这样您只需要一个addException(Exception e) 方法。

您甚至可以创建一个属性文件,其中包含针对每种异常类型的本地化消息并默认记录该消息。

您也可以查看@perception建议的链接:

Counting the number of exceptions happening in catch block

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-22
    • 1970-01-01
    • 1970-01-01
    • 2012-02-12
    • 1970-01-01
    • 2014-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多