0

I am out of curiosity about my code. I used a setter which includes throw exception for a class, and used a try-catch box inside the test class. I am not sure whether the throw part works well (does it work right?)or should I add 'throws'before 'if'statement, and I want to know what I should do to make it more effecient. These are my codes. Thank you for reading my question.

//setter of the IceCream class, and the setter includes throw exception 
public void setFlavor(int t){
    if(//code)
    {
    }
    else{
       throw new IllegalArgumentException(toString());
    }


//testing class
try{ 
            IceCream ice = new IceCream();
            p.setFlavor();     
        }
        catch (IllegalArgumentException ex){
            System.out.println(ex);
        }
Shirley
  • 41
  • 5
  • This [link](http://stackoverflow.com/questions/14973642/how-using-try-catch-for-exception-handling-is-best-practice) will help you. – Fady Saad Apr 27 '17 at 05:41
  • also `p.setFlavor();` does not call `setFlavor(int t)` they are different methods – Scary Wombat Apr 27 '17 at 05:44
  • 1
    @ScaryWombat it could (for documentation) but it is not necessary. – AxelH Apr 27 '17 at 05:45
  • 2
    It's a good idea, in an `IllegalArgumentException`, to use a message to indicate what the illegal argument was, and what it should have been. For example, `if(t < 1 || t > 10) { throw new IllegalArgumentException("The flavour must be a number between 1 and 10, but you passed " + t ); } `. This will make debugging much easier. – Dawood ibn Kareem Apr 27 '17 at 05:50
  • 2
    You don't need to worry about efficiency for trivial practice code like this. – Kayaman Apr 27 '17 at 06:13

0 Answers0