在if-else块中抛出异常

psu*_*003 3 c# exception-handling c#-3.0

首先,我意识到可能有更好的方法来做到这一点,而不是抛出异常我应该更好地处理这个条件.话虽这么说,我遇到了一些意想不到的行为,我更好奇为什么会这样,而不是使用它我的应用程序.

在方法中,我试图访问用户提供的文件.在方法开始时,我正在检查以确保文件的路径不是,Null或者String.Empty如果是,则抛出异常.当我测试时,我发现无论条件如何都会抛出异常.这是正常的行为,还是我错过了什么?

public static XElement Foo(String path)
{
    if (String.IsNullOrEmpty(path))
    {
       throw new ArgumentNullException(); // this exception is thrown  
                                          // regardless of the value of 'path'
    }


    // code to open and parse file
    // returns XElement
}
Run Code Online (Sandbox Code Playgroud)

更新:

在我的测试场景中,调用方法只是发送一个我为测试硬编码的默认路径.我还没有完成UI,因此用户定义路径的代码不完整.

private const string c_fooPath = "C:\\test\\text.txt"

public void CallingFoo()
{
    var xml = Foo(c_fooPath)

    // some code

}
Run Code Online (Sandbox Code Playgroud)

更新#2:

只是提一下我尝试过的其他一些测试.我试过了

if (String.IsNullOrEmpty(path))
{
    Console.WriteLine("testing")       // this line is skipped when my condition is
                                       // false but runs when  i force it to be true

    throw new ArgumentNullException(); // this exception is thrown  
                                       // regardless of the value of 'path'
}

if (false)
{
    throw new ArgumentNullException(); // the exception is not thrown here - the only
                                       // condition i have found so far.
}

public static XElement Foo(String path)
{
    path = "test";

    if (String.IsNullOrEmpty(path))
    {
       throw new ArgumentNullException(); // exception is still thrown  
    }


    // code to open and parse file
    // returns XElement
}
Run Code Online (Sandbox Code Playgroud)

Seb*_*ler 5

我给你的代码一个快速测试,它按预期工作,即如果字符串为null或空,则只抛出异常.调试代码以查看给定路径实际上是否包含内容且确实不为空或为空.也许在函数的调用者中也可能出现问题.

我的testcode(返回void而不是你的XElement):

class Program {
    static void Main(string[] args) {
        Foo("test");
    }

    public static void Foo(String path) {
        if (String.IsNullOrEmpty(path)) {
            throw new ArgumentNullException();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

你也可以试试Convert.ToString((object)stringVar) == ""而不是String.IsNullOrEmpty.

更新:也许这有帮助.