I'm fairly new to Java, and I'm trying to get my head around exceptions and when they should be used. I have been using them as a form of error checking, but I've come across several people saying that exceptions should only be used for things out of the program's control, such as user error.
I have a function which, for a given line in 2 dimensions, calculates all the y values between xMin and xMax. This function throws an exception if the line is vertical, as it is impossible to calculate all values of y on a vertical line. There is an equivalent function finding points between two y values as well, which throws an error if the line is horizontal.
findPointsInRangeOfX (int xMin, int xMax) throws LineIsVerticalException {
// check if line is vertical
// if vertical, throw an exception
// else calculate the y values for each integer between xMin and xMax
// return y values
}
I call this function as part of finding all the points on a line within a given window, given by a minimum and maximum x and y value. I don't check whether the line is vertical in this function; instead, I rely on the checking in findPointsInRangeOfX and use a try and catch block around the method.
pointsInWindow (int xMin, int xMax, int yMin, int yMax) {
try {
// Find list of all the points between xMin and xMax.
// Remove from list all points not between yMin and yMax
}
catch (LineIsVerticalException e) {
// If line is vertical, cannot find points between xMin and xMax
try {
// Instead, find list of all points between yMin and yMax
// Remove from list all points not between xMin and xMax
}
catch (LineIsHorizontalException e) {
// This part will never be reached because the line is vertical
// But the compiler complains if the exception isn't caught
}
}
}
Is this ok? I'm not throwing the exception for an error as such - there's nothing wrong with having a vertical line - but I'm using it to tell pointsInWindow that it needs to find the points between the y values rather than the x values. Should I be duplicating the check to see if the line is vertical in the pointsInWindow function rather than using a try catch block? If I did duplicate the check, should I get rid of the LineIsVerticalException all together?