[英]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.