也許你可以做這樣的事情(適應自己使用):
class Program
{
public int Divide_InExternalLib(int a, int b)
{
Console.WriteLine(string.Format("a={0}, b={1}", a, b));
int result = a/b;
Console.WriteLine(string.Format("Result = {0}", result));
return result;
}
public void CallExternalFunction(Action funct)
{
try
{
funct.Invoke();
}
catch (Exception ex)
{
Console.WriteLine(string.Format("Exception caught: {0}", ex.ToString()));
}
}
static void Main(string[] args)
{
var p = new Program();
int a = 6;
int b = 2;
p.CallExternalFunction(() => { p.Divide_InExternalLib(a, b); });
b = 0;
p.CallExternalFunction(() => { p.Divide_InExternalLib(a, b); });
Console.ReadLine();
}
}
輸出
a=6, b=2
Result = 3
a=6, b=0
Exception caught: System.DivideByZeroException: Attempted to divide by zero.
at GenericExceptionHandling.Program.Divide_InExternalLib(Int32 a, Int32 b) in
c:\users\siebiers\documents\visual studio 2015\Projects\GenericExceptionHandlin
g\GenericExceptionHandling\Program.cs:line 16
at GenericExceptionHandling.Program.<>c__DisplayClass2_0.<Main>b__1() in c:\u
sers\siebiers\documents\visual studio 2015\Projects\GenericExceptionHandling\Gen
ericExceptionHandling\Program.cs:line 41
at GenericExceptionHandling.Program.CallExternalFunction(Action funct) in c:\
users\siebiers\documents\visual studio 2015\Projects\GenericExceptionHandling\Ge
nericExceptionHandling\Program.cs:line 26
你要執行完全相同的代碼來響應完全相同的異常,只有在對其他庫的不同調用期間纔會發生?我的意思是,「ExceptionA」在所有案例中都有相同的答案嗎? –
全局異常處理程序可能有幫助,如果它適合你的上下文,它的異常處理大致相同(如日誌記錄等)。 –