I am writing an app and I want to load a file based on a path provided by the user. I check the extension of the file and when the extension does not match anything I recognize I want to throw an exception.
I could throw an IOException. But, I figured there could be a more detailed exception derived from that. So I looked at MSDN and found FileLoadException. The name suggests that my error would fit in this category, but…. when I look on MSDN it says: “Represents the error that occurs when a Assembly file is found but cannot be loaded.” and “The exception that is thrown when a managed assembly is found but cannot be loaded.” That is absolutely not what is the case with my error.
So what is the question then? Well, I wonder if the documentation actually means that the exception is meant to be thrown for this purpose only or that they just mean that they throw that exception in that specific case, but do not really specify when others should throw it.
On the IOException page on MSDN it does advice to use FileLoadException where appropriate:
IOExceptionis the base class for exceptions thrown while accessing information using streams, files and directories.The Base Class Library includes the following types, each of which is a derived class of
IOException:
- DirectoryNotFoundException
- EndOfStreamException
- FileNotFoundException
- FileLoadException
- PathTooLongException
Where appropriate, use these types instead of IOException.
Summarized: In case of an unknown file extension, should I throw an IOException or a FileLoadException (I do not want to define my own exception).
Thanks in advance.
You should throw
IOException, and never throwFileLoadExceptionwhich is very specific and “technical” (whereas your exception should be “application oriented”). Try to analyzeFileLoadExceptiontype withReflector(in mscorlib), you’ll see that it’s only used for the purpose defined in the msdn. Then imagine one day your code used in a “plugin context”, how will react the host program catching aFileLoadExceptionmeaning an assembly failed to load properly …