Page 1 of 1
About Question enthuware.ocajp.i.v7.2.1030 :
Posted: Tue Oct 02, 2012 12:53 am
by ETS User
Why will the first code throw AssertionError and not Exception.
Re: About Question enthuware.ocajp.i.v7.2.1030 :
Posted: Tue Oct 02, 2012 8:04 am
by admin
There only 4 members in the given enum and there is a case for each of them. Therefore, there is no way the control can enter the default block. And that is what you are trying to assert.
Throwing an Exception is not appropriate because you are not validating input parameters here. If you had only 3 cases, and if you didn't want any one to pass the 4th value, then throwing an exception in that case would be appropriate.
HTH,
Paul.
Re: About Question enthuware.ocajp.i.v7.2.1030 :
Posted: Sun Feb 17, 2013 1:04 pm
by zzantonni
Hi Paul,
from the question i don't understand that those are THE ONLY 4 valid members, i just see that those are 4 of the valid memebrs.
What if the enum has also a JOLLY member, and JOLLY should not be allowed in that piece of code?
I think IllegalArgumentException should be more appropriate in that scenario.
Thanks!
Re: About Question enthuware.ocajp.i.v7.2.1030 :
Posted: Sun Feb 17, 2013 4:25 pm
by admin
That is a very good point, zantonni. You are right, in that case IllegalArgumentException would be more appropriate. The question has been updated to make it clear that these are the only 4 valid values.
thank you for your feedback!
Paul.
Re: About Question enthuware.ocajp.i.v7.2.1030 :
Posted: Sat Mar 09, 2013 1:08 pm
by Robyn
I'm still completely confused by this question.
I have read the docs that it says to read at the bottom of the question, (in the Enthu study references section) and they state this:
"Note that the programmer does not explicitly throw AssertionError using the throw keyword."
Also - any argument which is not one of the 4 enums would surely be an illegal argument wouldn't it?
So why is the correct answer to throw an AssertionError, and not throw an IllegalArgumentException?
I can find nothing anywhere online which explains this.
Thanks
Re: About Question enthuware.ocajp.i.v7.2.1030 :
Posted: Sat Mar 09, 2013 1:09 pm
by Robyn
Sorry - the post above is referring to the first question on the D&D, with the switch statement..
Re: About Question enthuware.ocajp.i.v7.2.1030 :
Posted: Sat Mar 09, 2013 2:54 pm
by admin
Assertions are used to verify assumptions that you know will most certainly hold true in any case.
IllegalArgument Exception is thrown explicitly to enforce the API contract. I.e. in cases when it is technically possible by the users of your class to break the contract and you want to prevent that from happening.
Thus, in this case AssertionError is more appropriate. It is not thrown explicitly but implicitly by using the assert statement.
-Paul.