C# DLL如何向调用应用程序返回错误?

3
我正在编写一个dll,它是一个访问数据库的包装器。由于我的背景是LAMP和Perl的Web开发人员,因此对于C#我还不太熟悉,我不确定在调用应用程序传递错误参数等情况下如何返回错误。目前除了可能使用一些msgbox或抛出一些异常外,我还没有想到其他办法。我不知道从哪里开始寻找帮助或资源。任何帮助都将非常有用 :) 谢谢~

最佳实践是抛出异常并在主机应用程序中处理它。 - Daniel
6个回答

12

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

4
我讨厌与库捆绑的对话框。 - ojblass
如果我使用反射动态添加dll文件,则不会抛出此错误,并且它会给我一个未经用户处理的异常错误,有任何想法吗?这是我的问题http://stackoverflow.com/questions/38816233/c-sharp-user-defined-exception-handling-for-erroe-from-dll-get-exception-was-unh?noredirect=1#comment65000685_38816233 - Aylian Craspa

3

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


2

2

那个链接是关于2003年的,它有点过时,因为它支持(而不是反对)ApplicationException,但是其他的建议似乎仍然适用。 - Brian

1

通常情况下,Dlls不应该创建任何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
    }
}

0

抛出新的异常?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接