【问题标题】:Illegal start of expression while throwing an exception?抛出异常时非法开始表达?
【发布时间】:2023-03-24 08:11:01
【问题描述】:

我在这部分代码中不断收到错误 Illegal start of expression。

switch(length) {
    case 1: if(message.equalsIgnoreCase("End")){    
        throws new AnotherException("Stop",true);
    } else {
        throws new AnotherException("Continue",false); 
    } 
    break;
}

特别是如果我添加

throw new AnotherException

有人可以解释导致此错误的原因吗?谢谢。

【问题讨论】:

  • “这部分”有点宽泛

标签: java exception switch-statement custom-exceptions throws


【解决方案1】:

您需要将关键字throws 更改为throw

当抛出异常时,throw 被使用,throws 被用于方法签名中以指示该方法的预期异常。

throws new AnotherException("Continue",false); 更改为throw new AnotherException("Continue",false);

【讨论】:

    【解决方案2】:

    各种错误:

    • 您的方法必须使用throws AnotherException处理异常
    • 使用throw 而不是throws
    • break 语句是无法访问的代码,并且不允许编译,因为 if 的两边都解决了抛出 Exception 的问题。

    所以你的代码必须是这样的:

    public static void main(String[] args) throws AnotherException {
        String message = "End";
        int length = 1;
        switch (length) {
        case 1:
            if (message.equalsIgnoreCase("End")) {
                throw new AnotherException("Stop", true);
            } else {
                throw new AnotherException("Continue", false);
            }
        }
    }
    

    【讨论】:

      【解决方案3】:

      使用 throw 而不是 throws。 Throws 用于在方法头之后声明抛出异常的可能性。

      yourMethod(...) throws AnotherException {
          //stuff....
      
          switch(length)
          {
              case 1: if(message.equalsIgnoreCase("End")){    
                          throw new AnotherException("Stop",true);
                      }
                      else{
                          throw new   AnotherException("Continue",false); 
                      } break;
      
          //stuff...
      }
      

      【讨论】:

      • 这显然只是一个例子来说明 throw/throws 的区别。
      • 好的,这段代码是一个不好的例子,因为不会编译,因此不能完全解决问题
      猜你喜欢
      • 2021-08-15
      • 2014-10-19
      • 1970-01-01
      • 2013-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-18
      • 1970-01-01
      相关资源
      最近更新 更多