C# -Why does System.IO.File.GetLastAccessTime return an expected value when the file is not found?

后端 未结 6 1600
野性不改
野性不改 2021-01-04 06:05

Please, explain your thoughts.

1.  DateTime dt = System.IO.File.GetLastAccessTime(\"C:\\\\There_is_no_such_file.txt\");
2.  DateTime dt = System.IO.File.Get         


        
6条回答
  •  情话喂你
    2021-01-04 06:37

    Well, I didn't write any of the System.IO library, so I can't claim to have the answer to what exceptions are thrown at what point. What qualifies as an exception will always be a decision for the developer to take.

    I can take a stab at the reasoning behind this, though.

    Having a file that doesn't exist may in a lot of cases be expected behavior. Having to hit the file system just to query whether a file exists, and then hit it again to get the access time for that file, might just have seemed like overhead, compared to simply hitting the file system once and verifying the result. If DateTime was nullable, this would probably have yielded null, just as one can imagine that IndexOf would have, instead of -1.

    In the second case, however, passing an invalid path is evidence that somewhere in your code, something is maknig an expectation about something that cannot possibly work, and it might arguably make sense to bring this to the attention of the developer, by means of throwing an exception.

提交回复
热议问题