I have read at many places including this – http://msdn.microsoft.com/en-us/library/seyhszts.aspx – that you should use exception handling when something is truly exceptional.
The .Net File.Open function throws FileNotFoundException, etc. instead of returning error codes. Now it can frequently happen that the filename passed does not exist. This does not appear to me a truly exceptional situation.
Why may be the reason behind File.Open not following exception handling best practices?
0
It is expected that you call File.Open(...)
only on files that you know (or expect) to exist. If you don’t know whether the filepath passed exists or not, you’re expected to call File.Exists(...)
before trying to open it.
If you try to open a file you expect to exist, but it doesn’t, that’s an exception.
3
The way exceptions are handled in .NET is materially different than the way they are handled in, say, Java. Exceptions in Java demand more from the programmer than .NET does, and so the argument could be made that you reserve exception handling in Java for the truly exceptional cases.
In .NET, an exceptional condition is one that you cannot reasonably recover from without user intervention. If the user passes the name of a file to a method which expects the file to exist, but the file doesn’t exist, that’s an exceptional condition.
As a programmer, you still have the option of checking for the existence of the file first, before calling the method that requires it.
In any case, the guidance that Microsoft offers seems relatively straightforward:
If the event is truly exceptional and is an error (such as an
unexpected end-of-file), using exception handling is better because
less code is executed in the normal case. If the event happens
routinely, using the programmatic method to check for errors is
better.