14

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"));
}
İsmail Y.
  • 3,579
  • 5
  • 21
  • 29
Eugene
  • 59,186
  • 91
  • 226
  • 333

4 Answers4

17

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");
}
Venkata Raju
  • 4,866
  • 3
  • 27
  • 36
14

This is because a ternary operator in java takes the form expression ? expression : expression, and you are giving a statement as the final part. This doesn't make sense as a statement doesn't give a value, while expressions do. What is Java meant to do when it finds the condition to be false and tries to give the second value? There is no value.

The ternary operator is designed to allow you to quickly make a choice between two variables without using a full if statement - that isn't what you are trying to do, so don't use it, the best solution is simply:

public static AppConfig getInstance() {
    if (mConfig != null) {
        return mConfig;
    } else {
        throw new RuntimeException("error");
    }
}

The ternary operator isn't designed to produce side effects - while it can be made to produce them, people reading it won't expect that, so it's far better to use a real if statement to make it clear.

Gareth Latty
  • 86,389
  • 17
  • 178
  • 183
5

In case it's helpful to someone, here is an answer using java 8+ Optional:

public static AppConfig getInstance() {
    return Optional.ofNullable(mConfig).orElseThrow(() -> new RuntimeException("error"));
}
mjj1409
  • 3,075
  • 6
  • 28
  • 28
0

You are trying to return a throw new RuntimeException("error"). That is why you are getting error. Because in true case you are returning AppConfig and in false case you are returning exception.

Ali Imran
  • 8,927
  • 3
  • 39
  • 50
Martol1ni
  • 4,684
  • 2
  • 29
  • 39