• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

question 10, chapter 6, answer E: assert or IllegalArgumentException?

 
Greenhorn
Posts: 19
1
Oracle Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Question 10 in chapter 6 asks:

10. Which of the following are true of the code? (Choose all that apply.)

   4:    private int addPlusOne(int a, int b) {
   5:       boolean assert = false;
   6:       assert a++ > 0;
   7:       assert b > 0;
   8:       return a + b;
   9:    }

A. Line 5 does not compile.
B. Lines 6 and 7 do not compile because they are missing the String message.
C. Lines 6 and 7 do not compile because they are missing parentheses.
D. Line 6 is an appropriate use of an assertion.
E. Line 7 is an appropriate use of an assertion.

In the answers is stated that E is correct because checking with assert an argument passed from elsewhere in the program is a good use of assertions.

But in the book is explicitly stated that, when checking method parameters, we should not use asserts, but we should throw IllegalArgumentException instead  (and I agree with that).


Why is there this discrepancy? Maybe it is because for the exam we should answer "Yes, it is appropriate", but in real life we should answer "No, throwing IllegalArgumentException is appropriate instead" ?
 
author & internet detective
Posts: 41860
908
Eclipse IDE VI Editor Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Luigi,
There's a subtle distinction here. For a public method, using an assert to check the parameter is bad. For a private method, it is different though. A private method is internal state of the program. Checking a private method parameter with an assert is just like checking state with an assert on a random line of the program. It just happens to be in a method.
 
Luigi Rubino
Greenhorn
Posts: 19
1
Oracle Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ok, I understand.
Thanks Jeanne
reply
    Bookmark Topic Watch Topic
  • New Topic