Vincent
Vincent

Reputation: 29

Try Catch doesnt try the second condition

i have 2 condition inside try which is ||. The first condition will not try to catch. But the second one, it does.

    private void ButtonExecute_Click(object sender, EventArgs e)
    {
        try
        {
            if (fbd[0].SelectedPath != null || fbd[1].SelectedPath != null)
            {
                SearchingPhoto();
            }
        }
        catch(NullReferenceException)
        { return; }
    }

Method in try will run if and only if fbd[0].SelectedPath is not equal to null.

case 1: if(fbd[0].SelectedPath != null || fbd[1].SelectedPath != null)OK

case 2: if(fbd[0].SelectedPath == null || fbd[1].SelectedPath != null)not OK

case 3: if(fbd[0].SelectedPath != null || fbd[1].SelectedPath == null)OK

case 4: if(fbd[0].SelectedPath == null || fbd[1].SelectedPath == null)not OK

//i want to run a method inside case 2:

Upvotes: 0

Views: 96

Answers (2)

Vincent
Vincent

Reputation: 29

here is my final method

    private void ButtonExecute_Click(object sender, EventArgs e)
    {
        if (fbd[0]?.SelectedPath != null || fbd[1]?.SelectedPath != null)
        {
            SearchingPhoto();
        }    
    }

Upvotes: 1

Ziv Weissman
Ziv Weissman

Reputation: 4536

You are not getting a NullReferenceException, that's why the catch does not "catch".

You will receive null reference exception if you are using a property of that instance and it is null for example:

fbd[0].SelectedPath.SomeProp //Will cause exception if fbd[0].SelectedPath is null

If you want to find out if one of them is null why not simply:

fbd[0].SelectedPath == null || fbd[1].SelectedPath == null

Of course fbd[i] can also be null and you will get exception if you are trying to read the property SelectedPath from it.

Added:

Always good practice is to check if the instance you are using is not null if there is a chance it will be.

if (fbd[0]!=null && fbd[0].SelectedPath != null || 
    fbd[1]!=null && fbd[1].SelectedPath != null) 
    {
      //Safe to use
    }

Upvotes: 6

Related Questions