Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
254 views
in Technique[技术] by (71.8m points)

c# - Is it ok to bubble up the exception to the top of the stack?

Is it ok to let exception bubble up to the top of the stack instead of catching it in every method?.. Should we do it in any case? ..Are there any subtle issues or side effects with this approach (e.g. loss of details of the exception, stack trace or inner exception details etc.) ?


Though my question is general, the scenario in my case at present is as follows:

I am moving existing WSE3 web service to the WCF and so y clients are WSE3 clients.

I have added a behavior so that the FaultException will be communicated to the client side whenever it occurs in the WCF service. When there is an exception in the OperationContract method, I get exception message at client side without any problem. But whenever it occurs in the methods other than the OperationContracts, I get security related problem somehow. I am not able to identify the exact cause.

However, as a work around I thought to throw exceptions from OperationContract only and let exceptions bubble up to the OperationContract.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...