0

I writing the following method:

public int count(int x){
 //method contents
}

The parameter x must be between 0 and 10, although anyone using this code wouldn't have an issue as anyone using this method would never have an x which does not fulfill the requirements. Catching and handling checked exceptions could be a bit tedious due to the number of times the "count" method would be called. What is the best way to enforce x is always between 0 and 10: checked exception, unchecked exception, or assertion?

Nick
  • 1,743
  • 6
  • 23
  • 38
  • duplicate of http://stackoverflow.com/questions/2389127/checked-and-unchecked-exceptions-and-design-thoughts?rq=1 http://stackoverflow.com/questions/1957645/when-to-use-an-assertion-and-when-to-use-an-exception?rq=1 http://stackoverflow.com/questions/5070932/java-unchecked-checked-exception-clarification?rq=1 and many others. –  Aug 04 '14 at 20:21
  • also, just read Effective Java, 2nd ed by Joshua Bloch - chapter 9 explains this matter in-depth. –  Aug 04 '14 at 20:30

2 Answers2

1
  • checked exceptions are definitely out of the question because they only make sense for events which can come about regardless of the validity of input1;
  • an unchecked exception makes sense as a validation error: for example throwing an IllegalArgumentException would be by the book;
  • Java assertions should only be used to assert method invariants, those that must hold whatever the input is. An assertion failure should mean that the "guilty part" is not the caller, but the method's code itself.

1 Josh Bloch, Effective Java, Item 41:

The burden [of checked exceptions] is justified if the exceptional condition cannot be prevented by proper use of the API and the programmer using the API can take some useful action once confronted with the exception. Unless both of these conditions hold, an unchecked exception is more appropriate.

William F. Jameson
  • 1,833
  • 9
  • 14
0

That depends a bit on your style but the most common way would be an unchecked exception.

I would code something like this:

public int count(int x){
 if (x < 0 || x > 10) {
     throw new IllegalArgumentException(...);
 }
 //method contents
}
shlomi33
  • 1,458
  • 8
  • 9