Page 1 of 1

About Question enthuware.ocpjp.v17.2.3709 :

Posted: Wed Oct 04, 2023 4:15 pm
by gurban.azimli
Hi, can you please clarify why this option is considered as correct?

Every case must return a value.


if the case statement throws an exception. How this can be considered as returning value?

Code: Select all

var a = SomeEnum.A;
        String s = switch (a){
            case A -> "ada";
            case C -> throw new RuntimeException("qweqe");
            case B -> "qwejqle";
        };
in this example I believe case C does not return value instead it throws an exception.

Please clarify...

Re: About Question enthuware.ocpjp.v17.2.3709 :

Posted: Fri Oct 06, 2023 3:52 am
by admin
The "must return a value" is applicable only when the expression evaluation is completed normally. In case of an exception, the expression does not complete normally.
It is like saying a method whose return type is String must return a String. But the following method will compile even though it does not return a String:
String m(){
if(true) throw new RuntimeException();
}

But your point is valid, the option should mention this possibility to be correct. Will update.

thank you for your feedback!

Re: About Question enthuware.ocpjp.v17.2.3709 :

Posted: Sun Apr 07, 2024 4:38 pm
by pavvel
Switch expression can return void. How about that?
This goes against the correct answer: Every case must return a value or throw an exception.

switch ("A"){
default -> System.out.println("");
}

Re: About Question enthuware.ocpjp.v17.2.3709 :

Posted: Sun Apr 07, 2024 11:21 pm
by admin
No, a switch expression cannot return void. It is not an expression in that case, it is a switch statement. Please go through the detailed explanation provided at the bottom of the question. It explains the difference between a switch statement and a switch expression.