我有一个类,用不同的方法读取文件,做同样的事情。我想使用try-catch块来处理异常。我想问一下,是否有任何方法可以让所有方法都进入一个try块中,因为每个方法都会给出相同的异常"file not found“。
发布于 2011-05-11 19:53:23
我更喜欢的处理方式是从它们中调用一个公共方法,这样每个(单独的)看起来就像:
try {
// code
} catch(SomeExceptionType ex) {
DoSomethingAboutThat(ex);
}然而,你也可以用委托来做这件事。
void Execute(Action action) {
try {
// code
} catch(SomeExceptionType ex) {
// do something
}
}和
Execute(() => {open file});发布于 2011-05-11 19:58:21
您可以使用此技术通过扩展方法对操作进行包装
public static class ActionExtensions
{
public static Action WrapWithMyCustomHandling(this Action action)
{
return () =>
{
try
{
action();
}
catch (Exception exception)
{
// do what you need
}
};
}
}
public class DummyClass
{
public void DummyMethod()
{
throw new Exception();
}
}然后调用它,如下所示:
DummyClass dummyClass = new DummyClass();
Action a = () => dummyClass.DummyMethod();
a.WrapWithMyCustomHandling()();所以基本上你可以用包装任何动作。
发布于 2011-05-11 19:51:51
如果我理解这个问题,你不能有一个单独的try catch块,但你可以从catch调用一个方法,这样所有的方法都将共享相同的异常处理:
try
{
.... your code
}
catch (SomeException e)
{
ExceptionHandler(e);
}https://stackoverflow.com/questions/5963722
复制相似问题