[英]What's a good way for a c# dll to return error to the calling application?
我正在編寫一個dll,它是訪問數據庫的包裝器。 我一般都是c#的新手,因為我的背景是用perl進行Web開發LAMP,我不知道什么是將錯誤返回到調用應用程序的好方法,以防它們將錯誤的參數傳遞給我的函數或者什么不是。
我現在不知道除了可能做一些msgbox或拋出一些例外,但我不知道從哪里開始尋找。 任何幫助或資源都將是有用的:)
謝謝〜
您可能不希望在dll中顯示消息對話框,這是客戶端應用程序的工作,作為表示層的一部分。
.Net庫程序集通常會將異常冒泡到宿主應用程序中,所以這就是我要看的方法。
public static class LibraryClass
{
public static void DoSomething(int positiveInteger)
{
if (positiveInteger < 0)
{
throw new ArgumentException("Expected a positive number", "positiveInteger");
}
}
}
然后由您的主機應用程序來處理這些異常,並根據需要記錄和顯示它們。
try
{
LibraryClass.DoSomething(-3);
}
catch(ArgumentException argExc)
{
MessageBox.Show("An Error occurred: " + argExc.ToString());
}
通常通過拋出ArgumentException或其子類之一來處理錯誤的參數。
你想拋出異常。
看到
http://msdn.microsoft.com/en-us/library/ms229007.aspx
對於最常見的框架異常,例如ArgumentException和InvalidOperationException。 也可以看看
查看類庫開發人員的設計指南: 錯誤提升和處理指南
Dll通常不應創建任何類型的UI元素來報告錯誤。 您可以拋出(與提升相同的意義)許多不同類型的異常,或創建您自己的異常,並且調用代碼(客戶端)可以捕獲並向用戶報告。
public void MyDLLFunction()
{
try
{
//some interesting code that may
//cause an error here
}
catch (Exception ex)
{
// do some logging, handle the error etc.
// if you can't handle the error then throw to
// the calling code
throw;
//not throw ex; - that resets the call stack
}
}
拋出新的例外?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.