I am tring to count
the number of exceptions
happening and log those exceptions
as well. So what I did is, I created one method addException
in which I am counting all the exceptions.
addException
method accepts two parameters, one is the String
, and other is the boolean flag
which means whether we want to terminate the program or not because of any exceptions. Meaning, if that flag is true, then I need to terminate the program whenever there are any exceptions.
So if you take a look into my below catch
block, I have addException
method call for counting the exceptions and below that method call I am logging the exceptions as well.
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);
}
}
Problem Statement:-
Now what I am looking for is-
Is there any more cleaner way of doing the same thing? Meaning right now I am counting the exceptions in a method and then printing out the exceptions in the next line inside the catch block.
Is it possible to do the both of the things in the same addException
method? And if the flag is true to terminate the program, then terminate the program with the proper logging as well.
What could be the best way to re write addException method
do this?