如果给定的值超出范围,则波动代码是假定抛出IllegalArgumentException的程序的一部分。但是,如果setTime()中的给定数字超出范围,则会在主方法中创建对象时返回相应的值,而不是所需的错误消息!是什么原因IllegalArgumentException返回在对象删除中给出的值
这里是代码:
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");
}
}
您的代码不会做任何事情如果值是超出范围。它必须抛出异常,但如果它们无效,则忽略这些值。 –
代码神奇地应该知道它必须抛出一个特殊的异常,如果它没有任何if条件? – John3136
那么我想添加异常错误! – zamzam