【问题标题】:What's a good way for a c# dll to return error to the calling application?c# dll 向调用应用程序返回错误的好方法是什么?
【发布时间】:2009-05-05 03:42:33
【问题描述】:

我正在编写一个 dll,它是一个访问数据库的包装器。而且我通常对c#很陌生,因为我的背景是使用perl进行Web开发LAMP,我不确定在调用应用程序将错误参数传递给我的函数或不传递错误参数的情况下,什么是返回错误的好方法.

我现在不知道除了可能做一些 msgbox 或抛出一些异常,但我不知道从哪里开始寻找。任何帮助或资源都会非常有用:)

谢谢~

【问题讨论】:

  • 最佳实践是抛出异常并在宿主应用程序中处理它。

标签: c# exception exception-handling error-handling


【解决方案1】:

您可能不想在 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());
}

【讨论】:

  • 我讨厌与库绑定的对话框。
  • 如果我通过使用反射动态添加 dll 文件,这个错误想要抛出,它给我一个错误作为用户未处理的异常,任何想法在这里我的问题stackoverflow.com/questions/38816233/…
【解决方案2】:

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
    }
}

【讨论】:

    【解决方案3】:

    查看类库开发人员的设计指南:Error Raising and Handling Guidelines

    【讨论】:

    • 该链接是针对 2003 年的,它提倡(而不是反对)ApplicationException 有点过时,但其余建议似乎仍然及时。
    【解决方案4】:

    错误的参数通常通过抛出 ArgumentException 或其子类之一来处理。

    【讨论】:

      【解决方案5】:

      你想抛出一个异常。

      http://msdn.microsoft.com/en-us/library/ms229007.aspx

      对于最常见的框架异常,例如 ArgumentException 和 InvalidOperationException。另请参阅

      http://msdn.microsoft.com/en-us/library/ms229030.aspx

      【讨论】:

        【解决方案6】:

        抛出新异常?

        【讨论】:

          猜你喜欢
          • 2013-06-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-10-25
          • 2021-06-05
          相关资源
          最近更新 更多