I just read in Code Complete that you should not use exceptions for flow control. I also know that the common advice is to use exceptions to handle “exceptional cases.” But I’m not sure how to apply this advice. Is it a good idea to use exceptions to check for invalid parameters in a constructor? For instance, I have an ExcelInputConverter that turns rows in a spreadsheet into Record objects (for manipulation). The constructor takes the name of an excel file as input. Should I use exceptions to check that the incoming strings are valid excel files? That the excel files exist? It seems like I should use exceptions here because if this happens, the class essentially can’t function.
Is it a good idea to check for invalid data within the class or outside of the class?
Public Sub New(filename as string) 'new excel input converter
If Not (Path.GetExtension(fileName) = ".xls" Or Path.GetExtension(fileName) = ".xlsx") Then Throw New Exception("Can't make an Excel input converter from a non-Excel file like " & inputFileName)
If Not (File.Exists(fileName)) Then Throw New Exception("This file does not exist. Can't make an Excel converter")
If an object cannot be constructed due to an invalid argument to a constructor, an Exception is appropriate. Most languages do not provide a different means of telling the object creator that something went wrong (other than perhaps setting an “Invalid” flag on the object, which I would not suggest).
.NET defines an ArgumentException for this type of situation.
The class is in the best position to know what data is valid for it. If the class evolves over time and the rules for valid data change, you don’t want to have to go change all of the code that uses that class to reflect that change.