[英]IllegalArgumentException return the value given in object decleration
the bellow code is part of a program that is suppose to throw an IllegalArgumentException if the given value is out of range. 波纹管代码是程序的一部分,如果给定值超出范围,则该程序会抛出IllegalArgumentException。 But instead, if the given numbers in setTime() is out of range, it would return the corresponding value when the object was created in the main method instead of the desired error message! 但是,相反,如果setTime()中的给定数字超出范围,则它将在main方法中创建对象时返回相应的值,而不是所需的错误消息! what is the reason 是什么原因
here is the code: 这是代码:
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");
}
}
You said it should throw the exception. 您说应该抛出异常。 So you shouldn't catch it inside the method. 因此,您不应该在方法内部捕获它。 Remove the try{...}catch{..} around the if 's 中频的周围移除try {...}赶上{..}
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();
}
}
You have to throw the exception. 您必须抛出异常。
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");
}
}
you need to update your code handle outside range values 您需要更新代码句柄超出范围值
eg: 例如:
if (hour > 0 && hour < 23 )
this.hour = hour;
else
throw new IllegalArgumentException();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.