This doesn't compile and gives the following error: Illegal start of expression
. Why?
public static AppConfig getInstance() {
return mConfig != null ? mConfig : (throw new RuntimeException("error"));
}
You can't throw an exception in a ternary clause. Both options must return a value, which throw new Exception(); doesn't satisfy.
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.
We can nest ternary operators to test multiple conditions.
The ternary operator, also known as the conditional operator, is used as shorthand for an if...else statement. A ternary operator is written with the syntax of a question mark ( ? ) followed by a colon ( : ), as demonstrated below. In the above statement, the condition is written first, followed by a ? .
You may write an utility method
public class Util
{
/** Always throws {@link RuntimeException} with the given message */
public static <T> T throwException(String msg)
{
throw new RuntimeException(msg);
}
}
And use it like this:
public static AppConfig getInstance()
{
return mConfig != null ? mConfig : Util.<AppConfig> throwException("error");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With