无法抛出IllegalArgumentException

时间:2014-02-21 03:53:44

标签: java exception throw throws

我需要程序接受3个测试分数,然后打印他们的平均值,但如果分数小于-1或大于100,则应抛出IllegalArgumentException。我可以打印出平均值,但是当测试-1或101时,它不会抛出异常。我做错了什么?

我对学习异常非常陌生,所以感谢任何帮助。

这是我的代码:

import java.util.Scanner;
import java.io.*;

public class TestScores
{
public static void main(String[]args)
{
    Scanner keyboard = new Scanner(System.in);

    int[]scores = new int [3];

    System.out.println("Score 1:");
    scores[0] = keyboard.nextInt();

    System.out.println("Score 2:");
    scores[1] = keyboard.nextInt();

    System.out.println("Score 3:");
    scores[2] = keyboard.nextInt();

    int totalScores = scores[0] + scores[1] + scores[2];
    int average = 0;

    if (scores[0] >= 0 && scores[0] <= 100 || 
        scores[1] >= 0 && scores[1] <= 100 ||
        scores[2] >= 0 && scores[2] <= 100)
    {
        try
        {
            average = totalScores / 3;
        }

        catch(IllegalArgumentException e) 
        {
            System.out.println("Numbers were too low or high.");
        }

        System.out.println("Average Score: " + average);
    }



} //end of public static void



} //end of TestScores

3 个答案:

答案 0 :(得分:2)

语法是

if (condition) {
    throw new IllegalArgumentException("message here");
}

答案 1 :(得分:2)

你几乎就在那里......在if你确保所有分数都在适当的范围内。

if失败时,您希望在else中抛出IllegalArgumentException,如下所示:

if (scores[0] >= 0 && scores[0] <= 100 || 
    scores[1] >= 0 && scores[1] <= 100 ||
    scores[2] >= 0 && scores[2] <= 100)
{
    average = totalScores / 3;        
    System.out.println("Average Score: " + average);
}
else 
{
   throw new IllegalArgumentException("Numbers were too low or high.");
}

答案 2 :(得分:1)

它可以捕获应用程序在try 块中抛出异常的异常。

try块中,我们只看到average = totalScores / 3;,它不会抛出任何异常。所以它没有抓到被抛出的任何东西。

您可以使用此功能抛出异常 - IllegalArgumentException

public static int getInputScore(Scanner keyboard) {
    int score = keyboard.nextInt();
    if (score < 0 || score >= 100) {
        throw new IllegalArgumentException(); 
    }
    return score;
}

并在main代码中使用它:

public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);

    int[] scores = new int[3];

    System.out.println("Score 1:");
    try {
        scores[0] = getInputScore(keyboard);
    } catch (IllegalArgumentException e) {
        System.out.println("Numbers were too low or high.");
        return;
    }

    System.out.println("Score 2:");
    try {
        scores[1] = getInputScore(keyboard);
    } catch (IllegalArgumentException e) {
        System.out.println("Numbers were too low or high.");
        return;
    }

    System.out.println("Score 3:");
    try {
        scores[2] = getInputScore(keyboard);
    } catch (IllegalArgumentException e) {
        System.out.println("Numbers were too low or high.");
        return;
    }

    int totalScores = scores[0] + scores[1] + scores[2];
    int average = totalScores / 3;
    System.out.println("Average Score: " + average);
}