无效异常
Invalid Exception
所以我为我正在进行的实验编写了这个异常:
public class InvalidDNAException extends Exception{
public InvalidDNAException(String message){
super(message);
}
}
然后尝试将异常放入我用于实验室的class
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
我是不是没有正确创建异常,或者我该怎么做才能解决这个问题?
您漏掉了关键字 new
。将您的行更改为
throw new InvalidDNAException("Invalid DNA String");
你忘记了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);
}
throw InvalidDNAException("Invalid DNA String");
不是有效语法
InvalidDNAException
是一个 class,您需要通过以下方式调用 构造函数 :
throw new InvalidDNAException("Invalid DNA String");
所以我为我正在进行的实验编写了这个异常:
public class InvalidDNAException extends Exception{
public InvalidDNAException(String message){
super(message);
}
}
然后尝试将异常放入我用于实验室的class
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
我是不是没有正确创建异常,或者我该怎么做才能解决这个问题?
您漏掉了关键字 new
。将您的行更改为
throw new InvalidDNAException("Invalid DNA String");
你忘记了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);
}
throw InvalidDNAException("Invalid DNA String");
不是有效语法
InvalidDNAException
是一个 class,您需要通过以下方式调用 构造函数 :
throw new InvalidDNAException("Invalid DNA String");