在if-else块中抛出异常

时间:2011-04-29 05:07:22

标签: c# exception-handling c#-3.0

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

在方法中,我试图访问用户提供的文件。在方法开始时,我正在检查以确保文件的路径不是NullString.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
}

更新:

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

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

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

    // some code

}

更新#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
}

2 个答案:

答案 0 :(得分:5)

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

我的测试代码(返回 void 而不是您的XElement):

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

    public static void Foo(String path) {
        if (String.IsNullOrEmpty(path)) {
            throw new ArgumentNullException();
        }
    }
}

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

更新:可能thisthis有帮助。

答案 1 :(得分:0)

试试这个:

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

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

    // some code

}

当声明具有斜杠(\)的字符串变量时,请使用以下任一方法:

1)private const c_fooPath = @"C:\test\text.txt"

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

希望它有所帮助!

感谢。

相关问题