Why method returns -1?
I read code from one book and have this method:
public int getScore(String name) {
try {
//some code here
return score;
} catch (Exception e) {
e.printStackTrace();
return -开发者_开发问答1;
}
}
Why this method in catch returns -1? Why not 5? Is that some convention?
-1 is a standard error code when the caller expects a positive int
but really in that case a wrapped RuntimeException
or a more specific one would have been much better
I'm assuming the author uses this code to make sure something gets returned, and the caller of getScore
can check to see if a score
was correctly called.
In code:
int theScore = getScore("My Name");
if(theScore == -1) {
// Oh no, there was an error!
}
We can use the check for -1 to make sure that the code knows when getScore
fails.
Why method returns -1?
Because it is very poorly designed to do so on any exception. The method would have been better designed by declaring it to throw the exception(s) of interest and specifically by not catching all the RuntimeExceptions
as well.
You are the one choosing what you want to return as you are the only one who knows how you want to handle that returned value. I personally use -1
too when I want to detect an error, and I know a lot of people doing the same.
The reason they picked -1 instead of 5 is because -1 is not a feasible score to return from the getScore method. Therefore, when you call the function, you can easily check if it was -1 returned or not.
If it was a function that could realistically return -1 for a successful run, -1 would be a poor choice of a flag indicator. A more appropriate choice, then, might be -9999 or something ridiculous.
The first problem is we don't know what the exceptions are. Catching every exception is a very poor decision. Those exceptions were thrown for a reason so you would know exactly what went wrong and can deal with it appropriately.
Bad:
public int getScore(String name) {
try {
int score = scores.getScoreForName(name);
return score;
} catch (Exception e) { // catches everything
e.printStackTrace();
return -1;
}
}
Marginally better...
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
}
}
Much better:
/**
* 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);
}
精彩评论