Java OCA OCP Practice Question 2434

Question

Which of the following options show appropriate usage of assertions? (Choose all that apply.)

// INSERT CODE HERE
    assert (b != 0) : "Can't divide with zero";
    return (a/b);
}
  • a public float divide(int a, int b) {
  • b public static float divide(int a, int b) {
  • c private static float divide(int a, int b) {
  • d private float divide(int a, int b) {


c, d

Note

Options (a) and (b) are incorrect because assertions must not be used to check method arguments for non private methods.

Non-private methods can be called by objects of other classes, and you can't validate their method arguments by using assertions.

Assertions can be disabled at runtime, so they aren't the right option to validate method arguments to public methods.

You should throw exceptions in this case.

For example, when you come across invalid values that are passed to a non-private method, you can throw an IllegalArgumentException.




PreviousNext

Related