0

Possible Duplicate:
shutdown wpf while messagebox open

I currently have code like this, but the problem is that even after I show the error in a MessageBox provided by NLog, I want to shut down the app, so the user can fix the problem, but the app continues after they click OK in the message box.

private void Load(string fileName)
    {
        try
        {
            var environments = GetEnvironments(fileName); 
        }
        catch (FileNotFoundException ex)
        {
            logger.Error(ex.StackTrace);
        }
        catch (Exception ex)
        {
            logger.Error(ex.StackTrace);
        }
    }
Community
  • 1
  • 1
Xaisoft
  • 45,655
  • 87
  • 279
  • 432

1 Answers1

5

The exception has been handled so will not bubble up.

You have several options:

  • Rethrow the exception after logging, causing the exception to continue bubbling up (and assuming there are no other exception handlers) and causing the process to abort with an unhandled exception:

    throw;
    
  • Shutdown explicitly using Environment.Exit

    Environment.Exit(-1);
    
  • Another option is Application.Shutdown:

    Application.Current.Shutdown();
    

Rethrowing will show an error to the user. The other two options will not.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • 1
    Is one preferred over the other, I also saw some code that was something like Application.ShutDown (I don't think it was exactly this...) – Xaisoft Oct 04 '12 at 15:59
  • It was this `Application.Current.Shutdown();` – Xaisoft Oct 04 '12 at 16:00
  • Can you elaborate on why `throw` does not allow the app ton continue? – Xaisoft Oct 04 '12 at 16:01
  • In my case, NLog displays a message box to the user, so I guess throw is not necessary here. – Xaisoft Oct 04 '12 at 16:01
  • @Xaisoft - Probably. And the error message that comes up is not very nice. `Environment.Exit` is good to give the calling process (if scripting the application, for example) an exit code, which could indicate the type of error. – Oded Oct 04 '12 at 16:03
  • Yes I noticed, thanks for the help. – Xaisoft Oct 04 '12 at 16:03
  • I noticed you can't call `Application.Current.Shutdown()` from a class library, so I guess Environment.Exist is sufficient in this case? – Xaisoft Oct 04 '12 at 16:13