c# - Throwing an Exception in an if-else block -


to start, realized there better way this, , rather throwing exception should handle condition better. being said, ran unexpected behavior , i'm more curious why happening using application.

in method, attempting access file provided user. @ beginning of method, checking make sure path file not null or string.empty , throwing exception if is. when testing, finding exception thrown regardless of condition. normal behavior, or missing something?

public static xelement foo(string path) {     if (string.isnullorempty(path))     {        throw new argumentnullexception(); // exception thrown                                             // regardless of value of 'path'     }       // code open , parse file     // returns xelement } 

update:

in testing scenerio, calling method sending default path hard coded test. have not completed ui, code user define path not complete.

private const string c_foopath = "c:\\test\\text.txt"  public void callingfoo() {     var xml = foo(c_foopath)      // code  } 

update #2:

just mention of other tests have tried. have tried

if (string.isnullorempty(path)) {     console.writeline("testing")       // line skipped when condition                                        // false runs when  force true      throw new argumentnullexception(); // exception thrown                                          // regardless of value of 'path' }  if (false) {     throw new argumentnullexception(); // exception not thrown here -                                        // condition have found far. }  public static xelement foo(string path) {     path = "test";      if (string.isnullorempty(path))     {        throw new argumentnullexception(); // exception still thrown       }       // code open , parse file     // returns xelement } 

i've given code quick test , works expected, i. e. throws exception if string null or empty. debug code see if given path has content , isn't empty or null. maybe there wrong in caller of function.

my testcode (returns void instead of xelement):

class program {     static void main(string[] args) {         foo("test");     }      public static void foo(string path) {         if (string.isnullorempty(path)) {             throw new argumentnullexception();         }     } } 

you try convert.tostring((object)stringvar) == "" instead of string.isnullorempty.

update: maybe this or this helps.


Comments