简体   繁体   中英

What's a good way for a c# dll to return error to the calling application?

i'm writing a dll which is a wrapper to a access database. and i'm pretty new to c# in general as my background is in web development LAMP with perl, i'm not sure what's a good way to return error to a calling app in case they pass the wrong parameters to my functions or what not.

I have no idea as of now except to probably do some msgbox or throw some exceptions but i don't know where to start looking. Any help or resources would be more than useful :)

thanks~

You probably don't want to display message dialogs from within your dll, that's the job of the client application, as part of the presentation layer.

.Net library assemblies typically bubble up exceptions to the host application, so that's the approach I'd look at.

public static class LibraryClass
{
    public static void DoSomething(int positiveInteger)
    {
        if (positiveInteger < 0)
        {
            throw new ArgumentException("Expected a positive number", "positiveInteger");
        }
    }
}

Then it's up to your host application to handle those exceptions, logging and displaying them as appropriate.

try
{
    LibraryClass.DoSomething(-3);
}
catch(ArgumentException argExc)
{
    MessageBox.Show("An Error occurred: " + argExc.ToString());
}

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

You want to throw an exception.

See

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

for the most common framework exceptions, such as ArgumentException and InvalidOperationException. See also

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

查看类库开发人员的设计指南: 错误提升和处理指南

Dlls generally should not create any kind of UI element to report an error. You can Throw (same meaning as raise) many different kinds of exceptions, or create your own and the calling code (client) can catch and report to the user.

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

抛出新的例外?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM