[英]Can't make my own custom exception. Please help me
When I try and make a catch statement using InvalidTestScore exception java won't allow me. 当我尝试使用InvalidTestScore异常创建catch语句时,java将不允许我使用。 However when I use IllegalArgumentException, java does allow me to make it.
但是,当我使用IllegalArgumentException时,java确实允许我这样做。
// George Beazer
public class TestScores2 {
public TestScores2(int[] arg) {
System.out.println(average(arg));
}
public int average(int[]arg)
{
int temp=0;
for (int i = 0; i < arg.length; i++) {
if(arg[i]<0 || arg[i]>100)
{
IllegalArgumentException e = new IllegalArgumentException();
throw e;
}
else
{
temp+=arg[i];
}
}
return temp/arg.length;
}
public static void main(String[] args) {
int []ar={4,78,33,89};
TestScores2 ts=new TestScores2(ar);
}
}
Runs fine 运行良好
However if i run 但是如果我跑
public class TestScores2 {
public TestScores2(int[] arg) {
System.out.println(average(arg));
}
public int average(int[]arg)
{
int temp=0;
for (int i = 0; i < arg.length; i++) {
if(arg[i]<0 || arg[i]>100)
{
InvalidTestScoreException e = new InvalidTestScore();
throw e;
}
else
{
temp+=arg[i];
}
}
return temp/arg.length;
}
public static void main(String[] args) {
int []ar={4,78,33,89};
TestScores2 ts=new TestScores2(ar);
}
}
I get can't find symbol. 我得到找不到符号。 What does it take to make your own custom exception .
创建自己的自定义异常需要什么?
InvalidTestScoreException e = new InvalidTestScore();
??? ??? shouldn't that be:
不应该是:
InvalidTestScoreException e = new InvalidTestScoreException();
As @Falmarri pointed out, you need to declare an InvalidTestScoreException class 正如@Falmarri指出的那样,您需要声明一个InvalidTestScoreException类
Here is what a revised version might look like: 修改后的版本如下所示:
public class TestScores2 {
public class InvalidTestScoreException extends RuntimeException {
//Constructors go here
}
public TestScores2(int[] arg) {
System.out.println(average(arg));
}
public int average(int[]arg)
{
int temp=0;
for (int i = 0; i < arg.length; i++) {
if(arg[i]<0 || arg[i]>100)
{
InvalidTestScoreException e = new InvalidTestScoreException();
throw e;
}
else
{
temp+=arg[i];
}
}
return temp/arg.length;
}
public static void main(String[] args) {
int []ar={4,78,33,89};
TestScores2 ts=new TestScores2(ar);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.