To start, I realized there is probably a better way to do this, and rather than throwing an exception I should just handle the condition better. That being said, I ran into some unexpected behavior and I'm more curious why this is happening than using it my application.
In a method, I am attempting to access a file provided by the user. At he beginning of the method, I am checking to make sure that the path to the file is not Null
or String.Empty
and throwing an exception if it is. When I was testing, I am finding that the exception is 开发者_JS百科thrown regardless of the condition. Is this normal behavior, or am i missing something?
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
}
UPDATE:
In my testing scenerio, the calling method is just sending a default path that i hard coded for the test. I have not completed the UI, so the code for the user to define the path is not complete.
private const string c_fooPath = "C:\\test\\text.txt"
public void CallingFoo()
{
var xml = Foo(c_fooPath)
// some code
}
UPDATE #2:
Just to mention some of my other tests i have tried. I have tried
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
}
I've given your code a quick test and it works as expected, i. e. throws only the exception if the string is null or empty. Debug your code to see if the given path actually has content and really isn't empty or null. Maybe there could also something wrong in the caller of the function.
My testcode (returns void instead of your XElement):
class Program {
static void Main(string[] args) {
Foo("test");
}
public static void Foo(String path) {
if (String.IsNullOrEmpty(path)) {
throw new ArgumentNullException();
}
}
}
You could also try Convert.ToString((object)stringVar) == ""
instead of String.IsNullOrEmpty
.
Update: Maybe this or this helps.
Try this:
private const c_fooPath = @"C:\test\text.txt"
public void CallingFoo()
{
var xml = Foo(c_fooPath)
// some code
}
When declaring string variables having slashes (\) use either of the following ways:
1) private const c_fooPath = @"C:\test\text.txt"
2) private const c_fooPath = "C:\\test\\text.txt"
Hope it helps!
Thanks.
精彩评论