无效的例外

时间:2016-03-21 20:50:27

标签: java oop exception custom-exceptions

所以我为我正在做的实验室编写了这个例外:

public class InvalidDNAException extends Exception{
   public InvalidDNAException(String message){
      super(message);
       }
}

然后尝试将异常放入我正在用于实验室的课程中

try { for (int i=0;i<nucleo.length();i++){
        //code to be implemented later
        else throw InvalidDNAException("Invalid DNA String");
      }
}
catch(InvalidDNAException e){
         System.out.print("Invalid string");
         System.exit(0);
}

我一直收到错误:

cannot find symbol
     else throw InvalidDNAException("Invalid DNA String");
                ^
  symbol:   method InvalidDNAException(String)
  location: class DNA

我是不是没有正确创建例外或我该怎么做才能解决这个问题?

3 个答案:

答案 0 :(得分:2)

您忘记了new

else throw new InvalidDNAException("Invalid DNA String");
//         ^^^ this is important

此外,您不应仅仅为了在同一方法中捕获它和System.exit而抛出异常。如果您不打算编写代码来正确处理已检查的异常,至少将其包装在未经检查的异常中,以便获得堆栈跟踪:

catch (InvalidDNAException e) {
         // You really ought to do something better than this.
         throw new RuntimeException(e);
}

答案 1 :(得分:0)

您错过了关键字new。将您的行更改为

 throw new InvalidDNAException("Invalid DNA String");

答案 2 :(得分:0)

throw InvalidDNAException("Invalid DNA String");不是有效的语法

InvalidDNAException是一个类,您需要通过执行以下操作来调用构造函数

throw new InvalidDNAException("Invalid DNA String");