简体   繁体   中英

How to pass exception message from DLL to main application

Let's say that I have a class in my dll file:

public ClassInDllFile()
{
    String str = "";
    try
    {
        str = someClassMethod();
    }
    catch (Exception e) // or more precised exception type
    {
        // some code
    }
}

I don't want to put exception message in MessageBox from Dll level (it requires additional references), but I would to pass it to some (on example) WinForm application.

You can just catch the exception in the WinForms class.

This means you should not catch the exception here, but in the WinForms class itself, where you can show a dialog.

You could use something like (I changed a bit of code from your example to improve naming):

public ClassInDllFile()
{
    # Other functions

    ///
    /// Might throw a ... exception
    ///
    public Run()
    {
        String str = someClassMethod(); # Might cause an exception

        # More code
    }

And in your WinForms class:

var instance = ClassInDllFile()
try
{
    instance.Run()
}
catch (Exception e) // or more precised exception type
{
    // Error handling code
}

# More code

Also it is a good idea to document the ClassInDllFile.Run function which type of exceptions it might generate to inform calling functions to act upon it.

There are several ways in which you could handle this.

One simple way is to just throw the exception, and handle it in the outer / calling class.

Another is to gather info from the exception in your catch clause (like ExceptionMessage, StackTrace, and perhaps InternalException ), and store these in properties that the the calling class can check. You might then also include a boolean property like Suceeded , which you set to false if an exception occurs. Then the calling class can check that property after making the call, and retrieve more details about the exception if it needs them.

You can manipulate this however you want. Experiment until you find a solution that fits your needs.

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