Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I throw an exception while using the ternary operator

Tags:

java

android

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"));
}
like image 803
Eugene Avatar asked Dec 15 '12 11:12

Eugene


People also ask

Can we throw exception in ternary operator?

You can't throw an exception in a ternary clause. Both options must return a value, which throw new Exception(); doesn't satisfy.

What are the three conditions in a ternary operator?

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.

Can ternary operator have multiple conditions?

We can nest ternary operators to test multiple conditions.

How do you use ternary operator to write else if condition?

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 ? .


1 Answers

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");
}
like image 102
Venkata Raju Avatar answered Sep 19 '22 06:09

Venkata Raju