我試圖弄清楚如何在 c# 的字典中保存例外。
例如,我嘗試:
Dictionary<Exception, Exception> myCustomExceptions = new()
{
{ DbUpdateException, CustomExceptionX },
{ InvalidOperationException, CustomExceptionY }
}
然后我嘗試做這樣的事情:
try
{
...
}
catch (Exception exception)
{
throw myExceptions[exception];
}
但是不幸的是,這不起作用......有人可以幫我解決這個特殊問題嗎?
uj5u.com熱心網友回復:
您需要存盤一個可以按需生成新例外實體的工廠。
Dictionary<Type, Func<Exception>> myCustomExceptions = new()
{
{ typeof(DbUpdateException), () => new CustomExceptionX() },
{ typeof(InvalidOperationException), () => new CustomExceptionY() }
}
try
{
...
}
catch (Exception exception)
{
var exceptionType = exception.GetType();
var factory = myExceptions[exceptionType];
var ex = factory();
throw ex;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/521049.html
標籤:C#例外试着抓
上一篇:在VisualStudioCode中使用Python互動式視窗捕獲SeleniumWebDriver例外很熱門?
下一篇:System.Data.SqlClient.SqlException:'關鍵字'order'附近的語法不正確。'C#桌面應用程式
