I have an error/exception that is thrown by a particular method. Any time this error occurs, I want to log it. Would it be good practice to log the error within the initial method, and then re-throw it? That way I would not need to log it in the catch statements of any function that calls this method.
It would look something like this:
public void doSomething() throws Exception{
try{
someFunction(); // throws Exception
} catch (Exception e){
logger.fatal(e.getMessage()); // always log this Excpetion
throw e;
}
}
My concern was the re-throwing of exact same error. I have not seen this done, and I wondered if it would be considered bad practice.
EDIT: I should add that this Exception should never ever happen. That might help understand this situation.
It really depends on your logging preferences. For example you database access layer may have a method that takes a
SQLquery as aStringas an argument and executes it in the DB. Now you may want to log anySQLExceptionin that layer and then wrap theSQLExceptionby a custom exception [like aDatabaseException] and then re-throw it back to the parent layer. You may also want to encapsulate some additional behaviour like aboolean shouldRetryin yourDatabaseExceptionobject so that the parent layer may retry the operation again. Logging theSQLExceptionright away will let you debug the issue more easily later.EDIT:
This approach makes more sense when your parent layer does an operation that might throw more than one kind of exception. For example, in the above scenario, the method that takes the
SQLquery might also throw aInvalidHostExceptionif the database manager is unreachable or aConnectionRefusedException, if the database manager refused connection due to overload. In such a case you might log the exception and then wrap it with the more generalDatabaseException. Also if the method threw aConnectionRefusedExceptionthen you might want to set theshouldRetryvariable to true; while the same will be false for aInvalidHostException. This allows the caller API to try to call the method again after sometime if the value ofshouldRetrywas set to true.NOTE: Except
SQLException, the rest are creations of my imagination. 🙂