开发者

Exit Application On Error in a C # Library

It is a silly question I admit. So, apologies if this wastes your time but I just cannot find out a solution.

A WinForm Application which has a Class Library. I use Log4Net dll for logging information.

On Button_Click, I call a function in the Class Library which might throw an error. So, I have the contents of the function inside a try-catch-finally block. In the catch, I write log statements (using Log4Net dll).

Now, that an error has occurred, I want a Message to be shown to the UI. And after a Message is shown, I want it to quit开发者_Go百科.

How do I pass the control from the catch block of the Class Library back to the Form code so that I display a message and then quit?


Just call throw without any parameters after you've logged the error in the exception handler in the class library and it'll rethrow the exact same exception with the same callstack etc.

Then let your form catch it and handle it as you want.


In the Class Library Method, in the catch, rethrow the exception, so that it can bubble up to the form.

In the form Button_Click wrap the Class Method call in a try catch, and in the catch display the message and exit.


The library should probably re-throw the exception after logging about it.

class Form 
{
    OnClick() 
    {
        try
        {
            library.Routine();
        }
        catch(Exception e)
        {
            // messagebox
            // exit
        }
    }
}

class Library 
{
    public void Routine() 
    {
        try
        {
            // stuff
        }
        catch(Exception e)
        {
            logger.error("error in routine", e);
            throw;
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜