捕获不同方法引发的相同异常?

Old*_*ool 3 c# exception

看看下面的代码,其中两个方法抛出相同类型的异常但完全具有不同的上下文.

class Test
{
 public void methodThrowingExceptionX()
 {
   //some code
   throw new X();
 }

 public void anotherMethodThrowingExceptionX()
 {
   //some code
   throw new X();  
 }
}
class TestClient
{
  private Test testObj = new Test();
  public Response TestMethodCaller() 
  {
    try
    {
       testObj.methodThrowingExceptionX();
       testObj.anotherMethodThrowingExceptionX();
    }

    catch(X xExceptionObj)
    {
      //this will catch X exception regardless from which method it is comming
      //How can i distinguish from where the exception is coming(which method is throwing)
      //so that i can return the Response object according to the context of the method which has thrown this exception?
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我上面遇到的问题catch是它X从两种方法中捕获了类型的异常.但是Response,当X异常来自不同的方法时,我的高级逻辑需要具有不同的对象(例如,具有不同的语言代码,不同的消息,异常原因的不同的应用程序特定代码),或者您可以说Responose应该根据上下文进行更改.

实现这一目标的最佳方法是什么?

编辑

以下代码告诉您我为什么要这样做

interface ICommand
{
    void execute();
}

//say we have some command implementation
class CommandA : ICommand 
{
  public void execute()
  {

    //some code 
    throw new X();
  }

}

class CommandB : ICommand 
{
  public void execute()
  {

    //some code 
    throw new X();
  }

}
class MacroCommand : ICommand
{
    List<ICommand> commands;

    public MacroCommand(List<ICommand> commands)
    {
        this.commands = commands;

    }
    public void execute()
    {
       foreach(ICommand command in commands)
       {

           //execute method of various commands can throw exceptions may of     same type say X.
           command.execute();
       }
    }
}

class Client
{

   List<ICommand> commands = new List<ICommand>();

   commands.Add(new CommandB());
   commands.Add(new CommandA());

   MacroCommand macroCommand = new MacroCommand(commands);

   try
   {

        macroCommand.execute();
   }

   catch(X xExceptionObj)
   {
     //How can i get the information which execute() actually thrown the exception??

   }

}
Run Code Online (Sandbox Code Playgroud)

Tim*_*ter 5

通常的方法是用自己的方法调用两个方法调用try...catch.在这种情况下,您始终知道导致异常的原因,您可以单独处理它.

如果你想避免这种不管什么原因,你可以使用Exception.TargetSite:

try
{
    testObj.methodThrowingExceptionX();
    testObj.anotherMethodThrowingExceptionX();
}
catch (X xExceptionObj)
{
    MethodBase site = xExceptionObj.TargetSite;

    switch (site.Name)
    {
        case nameof(testObj.methodThrowingExceptionX):
            return blah....
        case nameof(testObj.anotherMethodThrowingExceptionX):
            return blub....
        default:
            throw new Exception("Unexpected method caused exception: " + site.Name);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 你应该编辑问题,而不是答案. (2认同)