General Follow-up Questions:
Collection<Element>
vsElements
for the parameter ofextractWeeks
: does this again relate to “use the broadest type of collection possible?- static member functions vs non-static: I’m confused over why certain functions (
extractWeeks
) were static, but others (weeklyResultUrl
) are not static. In both cases, the object doesn’t directly call it, so wouldn’t it make sense to declare all such functions as static? noEmptyElseThrow
strictly isn’t an IOException, is it? Can I throw other exceptions instead (IllegalArgumentExcpetion or NullPointerException, and I’m not sure which is the more suited of the two?); if so would the caller have to rethrow them?
Improving exceptions - ScraperException
Questions:
I built a custom exception ScraperException that enriches the exception with an informative message, like so:
public class ScraperException extends Exception {
final String message;
public ScraperException (String message) {
this.message = message;
}
@Override
public String toString() {
return this.message;
}
}
My idea is to then throw ScraperException
to the caller each time, wrapping other exceptions like IOException
in it. See the code below:
private List<String> loadWeeks() throws ScraperException {
final Document document = loadDocument(urlPrefix);
final Elements elements = selectRankingWeeksElements(document);
final List<String> weeks = extractWeeks(elements);
return noEmptyElseThrow(weeks);
}
private Document loadDocument(final String url) throws ScraperException {
try {
return Jsoup.connect(url).timeout((int) timeout.toMillis()).get();
} catch (IOException e) {
throw new ScraperException("Error loading ATP website: " + e.toString());
}
}
private static List<String> noEmptyElseThrow(final List<String> weeks) throws ScraperException{
if (weeks.isEmpty()) {
throw new ScraperException("Please provide a historical time range! Cannot rank otherwise!");
} else {
return weeks;
}
}
...and so on. For the most part I like this idea, but the single try-catch block in loadDocument
is irking me a great deal. Is there a more elegant way to do that?
There's something to be said about throwing a checked exception, which might be some further reading points as well.
I did some research on this, and it seems like this is generally a drawback of checked exceptions, in that wrapping them will result in boilerplate try-catch clauses. Is this unavoidable?