What's a good way for a C # dll to return an error to the calling application?
I am writing a dll that is a wrapper around an access database. and I'm pretty new to C # in general, since my background is in LAMP web development with perl, I'm not sure if there is a good way to return an error to the calling application if they pass the wrong parameters to my functions or what not.
I have no idea how it is now, except that it is possible to do some kind of msgbox or throw some exceptions, but I don't know where to start looking. Any help or resources would be more than helpful :)
thanks ~
source to share
You probably don't want to display message dialog boxes from your DLL, which is the client application's task as part of the presentation layer.
... Library assemblies tend to throw exceptions for the host application, so the approach I would look at.
public static class LibraryClass
{
public static void DoSomething(int positiveInteger)
{
if (positiveInteger < 0)
{
throw new ArgumentException("Expected a positive number", "positiveInteger");
}
}
}
It then walks over to your host application to handle these exceptions, register and display them as needed.
try
{
LibraryClass.DoSomething(-3);
}
catch(ArgumentException argExc)
{
MessageBox.Show("An Error occurred: " + argExc.ToString());
}
source to share
You want to throw an exception.
Cm
http://msdn.microsoft.com/en-us/library/ms229007.aspx
for the most common framework exceptions such as ArgumentException and InvalidOperationException. See also
source to share
Check out the Design Guide for Class Library Developers: Efficiency and Handling Guide
source to share
Dlls usually shouldn't create any UI element for the error message. You can "Throw" (the same value as raise) many different kinds of exceptions, or you can create your own, and the caller (client) can catch and inform 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
}
}
source to share