嗯,我找不到错误:
package udemy;
public class ClassOne {
private int positiveNum;
public ClassOne (int positiveNum){
if (positiveNum< 0 ){
throw new IllegalArgumentException("positiveNum should be greater than 0");
}
this.positiveNum= positiveNum;
}
public int getNum(){
return positiveNum;
}
}
在我的主要课程中,我得到了这段代码:
package udemy;
public class ClassTwo {
public static void main (String[] args) {
ClassOne number= new ClassOne(-15);
try {
System.out.printf("%s%n",number.getNum());
}
catch(IllegalArgumentException e)
{
System.out.printf("%s",e.getMessage());
}
}
}
但我得到以下输出:
Exception in thread "main" java.lang.IllegalArgumentException:positiveNum should be greater than 0
at udemy.ClassOne.<init>(ClassOne.java:11)
at udemy.ClassTwo.main(ClassTwo.java:7)
而不是说那个数字应该大于0。 哪里有错误?
答案 0 :(得分:5)
据说它应该大于0.
线程中的异常&#34; main&#34; java.lang.IllegalArgumentException:在udemy.ClassTwo.main(ClassTwo.java:7)的udemy.ClassOne。(ClassOne.java:11) positiveNum应该大于0
但真正的问题是你应该在try块中创建值,如下所示:
package udemy;
public class ClassTwo {
public static void main (String[] args) {
try {
ClassOne number= new ClassOne(-15);
System.out.printf("%s%n",budala.getNum());
}
catch(IllegalArgumentException e)
{
System.out.printf("%s",e.getMessage());
}
}
}
答案 1 :(得分:2)
这不是问题。未捕获的异常的标准显示是:
Exception in thread "main" java.lang.IllegalArgumentException:positiveNum should be greater than 0 at udemy.ClassOne.(ClassOne.java:11) at udemy.ClassTwo.main(ClassTwo.java:7)
或
Exception in thread "threadName" ExceptionType:message
at StackTraceElement
at StackTraceElement
...
如果您想要具有不同的外观,则必须在try块中捕获异常。
//...
try {
ClassOne number= new ClassOne(-15);
System.out.printf("%s%n",budala.getNum());
}
catch(IllegalArgumentException e)
{
System.out.printf("%s",e.getMessage());
}
// ...