Is it ok to let exception bubble up instead of catching it in every method?
Please Don't catch excpetions in every method! - you should only ever catch exceptions if you can do something useful with it, for example:
- Handle it (i.e. not rethrow it)
- Add some important contextual information
I've maintained applications where every nethod was surround with a try-catch
block, and I literally mean every method:
public void DoSomething()
{
try
{
throw new NotImplementedException();
}
catch (Exception ex)
{
throw ExceptionHandler.CreateException(ex, "DoSomething");
}
}
Catching exceptions like this is utterly pointless and does nothing except make your code harder to read and your exceptions harder to trace.
In the case where you exception has to pass some interprocess boundary (such as in a WCF service) then at the point where your exception is exposed to the world you might want to first catch, log and then rethrow the exception in a compatible format for the IPC boundary so that you have a log of all failures in your servivce
In many cases however there is an alternative mechanism designed for just this purpose- WCF has the IErrorHandler interface which can be registered to catch and log all unhandled exceptions in a consistent way without needing a try-catch block in each exposed method.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…