要求以下3个处理抛异常的时候,调用同一个处理(形如MyException),不希望在每个方法里加try-catch。
请教该怎么实现。 private void MyException(Exception e)
{
Console.WriteLine(e.ToString());
}-----------------------------------以下3个方法,参数,返回值不一样-----
private void Test1(string a1)
{
//业务处理
} private void Test2()
{
//业务处理
} private string Test3(string a2,string a3)
{
//业务处理
return "";
}
----------------------------------------------------------------------------
请教该怎么实现。 private void MyException(Exception e)
{
Console.WriteLine(e.ToString());
}-----------------------------------以下3个方法,参数,返回值不一样-----
private void Test1(string a1)
{
//业务处理
} private void Test2()
{
//业务处理
} private string Test3(string a2,string a3)
{
//业务处理
return "";
}
----------------------------------------------------------------------------
{ Test1("1");
Test2();
Test3("1","2"); Console.ReadLine();
} /// <summary>
/// 捕获下列3个Test方法异常
/// </summary>
/// <param name="e"></param>
private void MyException(Exception e)
{
Console.WriteLine(e.ToString());
} private static void Test1(string a1)
{
//业务处理
if (true)
{ }
else
{
throw new Exception("");
}
} private static void Test2()
{
//业务处理
if (true)
{
}
else
{
throw new Exception("");
}
} private static string Test3(string a2, string a3)
{
//业务处理
if (true)
{
return "";
} else
{
throw new Exception("");
}
}
{ try
{
Test1("1");
}
catch (Exception)
{ throw;
} try
{
Test2();
}
catch (Exception)
{ throw;
} try
{
Test3("1", "2");
}
catch (Exception)
{ throw;
}
Console.ReadLine();
}
private static void GuardedExec(Action action)
{
try
{
action();
}
catch (Exception e)
{
MyException(e);
}
}static void Main()
{
GuardedExec(() =>
{
Test1("1");
}); GuardedExec(() =>
{
Test2();
}); string result = "";
GuardedExec(() =>
{
result = Test3("1", "2");
});
}不想用Lambda的话,也可以用匿名方法:
GuardedExec((Action)delegate
{
Test1("1");
});
这个方法我也用了,不知有没更好的方式,即在调用方法的方法体外,可否定义某个XX,自动捕获此方法抛出的异常。
捕获的异常是未知的。