Throwing Exceptions
Your own methods can reject invalid arguments with throw. The exception type and message should explain the violated contract.
Failing close to the bad value prevents invalid state from traveling deeper into the program, where it would be harder to diagnose.
Reject a bad argument
public class Main {
static int share(int slices, int people) {
if (people <= 0) {
throw new IllegalArgumentException(
"people must be positive");
}
return slices / people;
}
public static void main(String[] args) {
try {
System.out.println(share(8, 0));
} catch (IllegalArgumentException error) {
System.out.println(error.getMessage());
}
}
}
Output:
people must be positive
Zero people cannot receive a share, so the method throws IllegalArgumentException. The catch block prints its message.
Use exceptions for exceptional failures, not ordinary branches such as a search that simply finds no match.
Throw IllegalArgumentException when a percentage falls outside 0 through 100.