尝试Catch没有尝试第二个条件

时间:2017-07-09 05:45:53

标签: c# winforms

我在试验中有2个条件是||。第一个条件不会试图抓住。但第二个,确实如此。

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

当且仅当fbd [0] .SelectedPath不等于null时,try中的方法才会运行。

案例1:if(fbd[0].SelectedPath != null || fbd[1].SelectedPath != null)确定

案例2:if(fbd[0].SelectedPath == null || fbd[1].SelectedPath != null)不行

案例3:if(fbd[0].SelectedPath != null || fbd[1].SelectedPath == null)确定

案例4:if(fbd[0].SelectedPath == null || fbd[1].SelectedPath == null)不行

//我想在案例2中运行一个方法:

2 个答案:

答案 0 :(得分:6)

你没有得到 NullReferenceException ,这就是catch没有“捕获”的原因。

如果您正在使用该实例的属性,并且它为null,则会收到空引用异常,例如:

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

如果你想知道其中一个是否为空,为什么不简单:

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

当然fbd [i]也可以为null,如果你试图从中读取属性SelectedPath,你会得到异常。

添加了:

总是良好的做法是检查您使用的实例是否有空(如果有可能)。

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

答案 1 :(得分:1)

这是我的最终方法

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