无法自己制作自定义异常。请帮我

时间:2011-02-07 22:59:28

标签: java arrays compiler-construction error-handling

当我尝试使用InvalidTestScore异常制作一个catch语句时,java将不允许我。但是当我使用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);
    }

}

运行正常

但是如果我跑

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);
    }

}

我得不到符号。如何制作自己的自定义异常。

2 个答案:

答案 0 :(得分:4)

InvalidTestScoreException e = new InvalidTestScore();

???不应该是:

InvalidTestScoreException e = new InvalidTestScoreException();

答案 1 :(得分:3)

正如@Falmarri指出的那样,你需要声明一个InvalidTestScoreException类

以下是修订版本的样子:

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);
    }

}