请看下面的代码,其中两个方法抛出了相同类型的异常,但上下文完全不同。
我遇到了一个问题,使用上述的
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?
}
}
}
我遇到了一个问题,使用上述的
catch
会捕获两个方法中类型为X
的异常。但是我的高级逻辑要求在不同的方法中产生X
异常时有不同的Response
对象(例如,具有不同的语言代码、不同的消息和不同的应用程序特定代码)。或者可以说,Response
应根据上下文而变化。
如何最好地实现这一点?
编辑
以下代码告诉您我为什么要这样做
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??
}
}
try...catch
中,这样你就知道它来自哪里了 ;) - Tim Schmelter