Exception handling no-nos

Just spotted this in a project I’m working on:

public static string GetExceptionAsString(this Exception exception){        return string.Format("Exception message: {0}. " + Environment.NewLine +                "StackTrace: {1}. {2}", exception.Message, exception.StackTrace,                GetAnyInnerExceptionsAsString(exception));}

Writing code like this should be a shooting offense.

But wait, there’s more! Check out its usage:

try{        ...}catch (Exception ex){        log.InfoFormat("Error occured:{0}.", ex.GetExceptionAsString());}


Code like this demonstrates a complete misunderstanding of CLR exception basics — inner exceptions and formatting — and also log4net. All that hand-rolled formatting could simply be replaced with:

  • GetExceptionAsString() -> Exception.ToString()
  • ILog.InfoFormat(format, args) -> ILog.Info(message, exception)