How important it is (in programming languages in generally actually) the exact type of exception type? Say I have a hierarchy of chapters of a book, and I use a method to access the chapters. One would be:
public void chapterSearch(int chapter) {
try {
chapterString = this.hierarchy.get(chapter).getText();
} catch(IndexOutOfBoundsException e) {
throw new....
}
}
The second is this:
public void chapterSearch(String chapterString) {
for(int i = 0; i < this.hierarchy.size(); i++) {
if(chapterString.equals(this.hierarchy.get(i).getText())) {
break;
} else if(i == this.hierarchy.size() - 1) {
throw new IllegalArgumentException...
}
}
}
In the first method, it is obvious throw a new IndexOutOfBoundsException
. But then there is the IllegalArgumentException
which you can use, which according to the javadoc is
Thrown to indicate that a method has been passed an illegal or inappropriate argument.
which seems quite appropriate for the situation, too. I mean, passing a very large chapter number where there is no such chapter number seems quite inappropriate to me. Or, as in the comments, I can throw my own new Exception, ChapterNotFoundException
. But this might be cumbersome, and I might not be using this Exception more than once -- it might then seem that using a pre-existing Exception is more apt.
But in general, even if in this case IndexOutOfBoundsException
remains most appropriate, or if you would prefer, ChapterNotFoundException
, how much does the choice of exception type matter in general?
I guess creating your own Exception type makes loads of sense once you use it a lot, but what if you aren't?
Edit: A good, related answer, though the answer below is very good as well, is here.