如果我為消費者撰寫了一個 dll,在 catch 范圍內,拋出例外還是將其寫入參考或輸出字串引數,哪個更好?
據我所知,例外確保失敗不會被忽視,因為呼叫代碼沒有檢查回傳碼。https://docs.microsoft.com/en-us/dotnet/standard/exceptions/best-practices-for-exceptions
以下兩個選項中哪個最好?
選項A
static void ThrowException(string value)
{
try
{
//Some code....
}
catch (Exception)
{
//Log Exception
throw;
}
}
選項 B
static void RefException(string value, ref string errorMessage)
{
try
{
//Some code...
}
catch (Exception ex)
{
//Log Exception
errorMessage = ex.ToString();
}
}
uj5u.com熱心網友回復:
我相信您正在尋找創建 .net 例外以外的自定義例外
使用以下代碼更新您的代碼并根據您的需要創建自定義例外。
public void ThrowException()
{
if (string.IsNullOrEmpty(value))
{
throw new NullException();
}
if (value.Length > 10)
{
throw new LengthException();
}
}
public class NullException : Exception
{
NullException() : base(NullException.GetMessage())
{
}
public static string GetMessage()
{
return "value is null or empty";
}
}
public class LengthException : Exception
{
LengthException() : base(LengthException.GetMessage())
{
}
public static string GetMessage()
{
return "value length greater then 10 exception";
}
}
uj5u.com熱心網友回復:
選項 A 當您驗證某些特定條件時,它將通過正確的錯誤訊息通知客戶端。雖然其他選項也通過拋出例外來做同樣的事情,但為驗證拋出例外并不是一個好習慣。如果應用程式中發生任何例外,拋出包含所有細節的例外并不是一個好習慣,因為它可能通過向客戶端應用程式提供不必要的細節而導致安全威脅。始終建議將其登錄并向客戶端應用程式顯示修改后的訊息。
在這種情況下,您應該使用 throw Exception,因為您可以將自定義訊息傳遞給客戶端應用程式,并且當您使用 ref 選項時,錯誤訊息可能會被應用程式的另一個組件修改,這可能會誤導例外資訊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/324107.html
