While working on a course (as in, school courses) database system for a school project, I stumbled upon an issue of debate.
I have a class called Course. Here is a constructor (the other one is a blank constructor that assigns default values) for the class:
public Course(String name, String code, char level, int academicYear)
{
serialNumber = nextSerialNumber++;
if (name == null)
{
throw new NullPointerException("Name can not be null.");
}
else
{
this.name = name;
}
if (code == null)
{
throw new NullPointerException("Code can not be null.");
}
else
{
this.code = code;
}
if (indexOf(level, VALID_LEVEL) == -1)
{
throw new InvalidLevelException("Level must be one of "
+ "characters defined in the public array in Course.");
}
else
{
this.level = level;
}
if (String.valueOf(academicYear).length() != NUMBER_OF_DIGITS_IN_YEAR)
{
throw new InvalidYearException("Year must be a four digit number!");
}
else
{
this.academicYear = academicYear;
}
}
Where
InvalidLevelException
and
InvalidYearException
are custom exceptions that are subclasses of
RuntimeException
I throw exceptions from that constructor to indicate if anything has gone wrong. For example, if, while reading from the data file, I encounter bad data, I can reject it and write it to a log (as the project mandates), simply by putting that constructor in a try-catch block and then catching those exceptions, and inside that catch block, log the bad data.
After showing this code to my teacher, he said it is inappropriate to throw exceptions from the constructor. However, I have read numerous Stackoverflow posts in which this practice is encouraged.
My question is: Is it okay to throw exceptions from the above constructor?
Reputable sources (for example, official documents or authoritative books) attached with an answer would be greatly appreciated.
Thanks very much in advance.