Carsten Ziegeler a écrit :
>
> Hi,
>
> I would like to know, if we should define a policy for logging exceptions.
> Currently, sometimes exceptions are logged when they are raised, sometimes
> when they are catched and sometimes they aren't logged at all.
>
> This leads to the problem, that you get the same exception more than once
> in the log or you never see it (ok, the first alternative is of course the
> better one );).
>
> Now, if we stick to a simple rule, we could easily have all exceptions in
> the log and these only once which would make reading the log files a little
> bit easier. So, there are two alternatives:
> a) always log an exception when it's raised but not when it's catched
> b) always log an exception when it's catched but not when it's raised
>
> I'm +1 on b).
>
> Opinions?
+1 on a)
Logging a message _and_ throwing an exception allows :
- have the log go into the logging category of the component that raised
the exception,
- the logging context can hold more information than the exception (see
logkit ContextMap).
Does b) means exceptions will be logged in each try/catch of the program
stack ? Did I miss something or is this what you want to avoid ?
My rule of thumb about exceptions is "catch exceptions only if you can
do something meaningful, otherwhise propagate it".
Some additional rules :
- never, never, never loose the original exception ! At least wrap the
it in a CascadingRuntimeException
- never cascade an exception that you throw (e.g. don't wrap a
ProcessingException inside a ProcessingException),
- propagate "as is" RuntimeExceptions.
A typical try/catch block could look as follows :
public void doIt() throws ProcessingException
{
try {
...
if (badCondition) {
String text = "Bad condition when processing xxx";
getLogger().warn(text);
throw new ProcessingException(text);
}
...
} catch(ProcessingException pe) {
throw pe;
} catch(RuntimeException re) {
throw re;
} catch(Exception e) {
String msg = "Caught an exception while yyy";
getLogger().warn(msg);
throw new ProcessingException(msg, e);
}
}
Developpers here most often point out the top-level exception when only
the bottom one is really meaningfull. Having to page down several times
to see it doesn't help in a fast and clear identification of problems ;)
This is why exception nesting should be limited as far as possible.
Sylvain
--
Sylvain Wallez
Anyware Technologies - http://www.anyware-tech.com
---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, email: [EMAIL PROTECTED]