所有錯誤資訊必須封裝在例外物件中。底層錯誤轉換為應用層例外時不得遺失資訊。呼叫端依據具體例外型別決定處理行為:
try { Foo(); Bar(); }
catch (MyFirstApplicationException e1) { FixProblem(e1); }
catch (AnotherApplicationException e2) { ReportErrorAndContinue(e2); }
catch (YetAnotherApplicationException e3) { ReportErrorAndShutdown(e3); }
catch (Exception e) { ReportGenericError(e); }
finally { CleanupResources(); }
若庫只拋出通用 Exception,呼叫端唯一選擇是掛起/中止程式,或解析 e.TargetSite.Name 猜測錯誤來源:
catch (Exception e)
{
switch (e.TargetSite.Name)
{
case "Foo": FixProblem(e); break;
case "Bar": ReportErrorAndContinue(e); break;
default: ReportErrorAndShutdown(e); break;
}
}
此做法極其脆弱,且無法應對更深層呼叫鏈。庫作者有責任提供豐富例外型別,讓使用者能精準處理。