IllegalArgumentException返回object decleration中给出的值

时间:2016-04-15 05:34:16

标签: java

下面的代码是程序的一部分,如果给定的值超出范围,则假定抛出IllegalArgumentException。但是,如果setTime()中的给定数字超出范围,则在main方法中创建对象而不是所需的错误消息时,它将返回相应的值!是什么原因

这是代码:

public class MyTime {

    private int hour = 0;
    private int minute = 0;
    private int second = 0;

    public static void main (String [] args) {
// when the value is out of range in setTime(), the value given bellow in t1 is returned
        MyTime t1 = new MyTime (10,10,10);
        t1.setTime(26, 23, 14);
        System.out.println("toString(): " + t1);   
    }

    public MyTime (int hour, int minute, int second) {
        this.hour = hour;
        this.minute = minute;
        this.second = second;
    }
    public void setTime (int hour, int minute, int second) {
        try {
            if (hour > 0 && hour < 23 ) {
                this.hour = hour;
            }

            if (minute > 0 && minute < 59 ) {
                this.minute = minute;
            }

            if (second > 0 && second < 59 ) {
                this.second = second;
            }            

        }
        catch (IllegalArgumentException exception) {
            System.out.println("Invalid entry");
        }
    }  

3 个答案:

答案 0 :(得分:1)

你说它应该 抛出 异常。所以你不应该在方法中 捕捉 它。如果 <<>> < < < / p>

public void setTime (int hour, int minute, int second) {

    if (hour > 0 && hour < 23 ) {
        this.hour = hour;
    } else {
        throw new IllegalArgumentException();
    }

    if (minute > 0 && minute < 59 ) {
        this.minute = minute;
    } else {
        throw new IllegalArgumentException();
    }

    if (second > 0 && second < 59 ) {
        this.second = second;
    } else {
        throw new IllegalArgumentException();
    }       

}

答案 1 :(得分:0)

你必须抛出异常。

public void setTime (int hour, int minute, int second) {
    try {
        if (hour > 0 && hour < 23 ) {
            this.hour = hour;
        }else{
            throw new IllegalArgumentException("Invalid Hour Value");
        }

        if (minute > 0 && minute < 59 ) {
            this.minute = minute;
        }else{
            throw new IllegalArgumentException("Invalid Minutes Value");
        }

        if (second > 0 && second < 59 ) {
            this.second = second;
        }else{
            throw new IllegalArgumentException("Invalid Seconds Value");
        }            

    }
    catch (IllegalArgumentException exception) {
        System.out.println("Invalid entry");
    }
}  

答案 2 :(得分:0)

您需要在范围值之外更新代码句柄

例如:

if (hour > 0 && hour < 23 )
    this.hour = hour;
else
    throw new IllegalArgumentException();