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

前端 未结 4 1075
南旧
南旧 2021-02-13 03:49

This doesn\'t compile and gives the following error : Illegal start of expression. Why?

public static AppConfig getInstance() {
        return mConf         


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-13 04:34

    You may write an utility method

    public class Util
    {
      /** Always throws {@link RuntimeException} with the given message */
      public static  T throwException(String msg)
      {
          throw new RuntimeException(msg);
      }
    }
    

    And use it like this:

    public static AppConfig getInstance() 
    {
        return mConfig != null ? mConfig : Util. throwException("error");
    }
    

提交回复
热议问题