开发者

How to return an exception thrown in one project to another?

is there any way to catch and return an exception thrown from one project to another?

For example, i'm keeping codes in different projects . Say A and B. If A is the engine part and B is the UI part, then an exception occurred in the engine should be caught in UI as w开发者_运维知识库ell.Please help.


The only reason you'd want to catch the exception in your engine code is if you thought you could handle it, or you needed to do some logging or something like that. There isn't much (any) benefit in catching simply to rethrow. However, assuming you have a valid reason, then in your UI code you can have

try
{
    engine.Start();
}
catch (SpecificException se)
{
    // Do stuff with specific exception
}
catch (Exception ex)
{
    // Show the user something unexpected happened 
}

In your Engine code, you can have;

public void Start()
{
    try
    {
        if (this.HasNoOil)
        {
            throw new SpecificException("Can't go without oil. We'll do some damage");
        } 
        // Other stuff
    }
    catch (Exception ex)
    {
        // Log details of exception and throw it up the stack
        throw;
    }
}


If you want to catch exceptions at the UI level you can not catch them at your engine level.

For the running application there is no difference in which assembly (every project creates an assembly) the exception was thrown.

If you really have to catch and re-throw the exception at your engine level re-throw correctly

catch(Exception ex) 
{ 
    // whatever logic
    throw;
}

or wrap it

catch(Exception ex) 
{ 
    // whatever logic
    throw new YourEngineException("Some Message", ex);
}   

If you just want to log it, don't do it, if it does not cross process boundaries.

Catch, log, re-throw is an anti pattern in my opinion. It just creates a bazillion log entries, catching at the highest possible level should be enough if you don't destroy the stack trace.

Use wrapping if you can provide extra information to the exception. For Example if you have one method which loads data, changes and saves it you could wrap the exception and add "Error '{0}' when saving" or something else. However don't forget to include the originating exception as inner exception.


In my view it is not possible, until unless these two application share same App domain. To make them part of single app domain you need do remoting or wcF kind of stuff, where you can share the objects between two projects.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜