Первая проблема - мы не знаем, что такое исключения.Поймать каждое исключение - очень плохое решение.Эти исключения были выдвинуты по какой-то причине, чтобы вы точно знали, что пошло не так, и могли бы правильно с этим справиться.
Плохо:
public int getScore(String name) {
try {
int score = scores.getScoreForName(name);
return score;
} catch (Exception e) { // catches everything
e.printStackTrace();
return -1;
}
}
Маргинально лучше ...
public int getScore(String name) {
try {
int score = scores.getScoreForName(name);
return score;
} catch(NameNotFoundException) {
e.printStackTrace();
return -2; // now we know what happened, not just a general error
} catch (Exception e) { // catches everything
e.printStackTrace();
return -1; // generally error
}
}
Намного лучше:
/**
* Get the score for a given name. Will throw a runtime exception if the
* name doesn't exist.
* @param name The name to get the score for
* @return the score for the name
* @throws NameNotFoundException if the name doesn't exist in the database.
*/
public int getScore(String name) {
return scores.getScoreForName(name);
}