Pankaj Upadhyay
Pankaj Upadhyay

Reputation: 13574

I am using try catch but it's still throwing an error in a WPF application

Here's the page constructor code

public DebitNoteCreation(int transactionID) :
        this()
    {
        try
        {
            InsertDebitNote dn = new InsertDebitNote();
            dn.Load(transactionID);
            this.DataContext = dn;
        }
        catch (Exception)
        {
            MessageBox.Show("Some of the entries for this transaction are empty so kindly complete them", "Error");
        }
        this.NavigationService.Navigate(new Uri("DisplayTransaction.xaml", UriKind.Relative));
    }

Error Message

Object reference not set to an instance of an object.

I am able to see the message box but after i click the ok button, it throws the above written error.

Upvotes: 1

Views: 517

Answers (2)

Marc Gravell
Marc Gravell

Reputation: 1062530

Since the error happens after you click OK, I expect that this.NavigationService is null, due to the failing constructor.

Also, you shouldn't assume that Exception means "Some of the entries for this transaction are empty so kindly complete them", and allowing a constructor to succeed when it has clearly failed to fully initialize an object is very dangerous.

In fact, only the UI should be doing message-boxes anyway. I would rewrite such that it throws a known exception after checking the transactions (i.e. the scenario you expect to be a problem). Let the UI catch that exception and do the message box there.

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1499730

If the exception is thrown so that the messagebox is shown, that suggests something went wrong... and you won't have assigned anything to this.DataContext. That could well cause follow-on errors.

Look at the stack trace of the NullReferenceException to see exactly what's throwing it, but basically you're trying to keep going with an incompletely-initialized object, which is rarely a good idea.

(Note that you should probably catch a more specific exception, and you should definitely log it rather than just showing a message box and then ignoring it.)

If you have to keep going, set the context to an empty note or something like that. I suspect you don't actually want to show the page in that case though. You may want to consider loading the transaction before constructing the page, to make things a bit cleaner.

Upvotes: 1

Related Questions