Java:正确的方式来抛出并捕获异常以验证输入 [英] Java: Proper way to throw and catch an exception to validate input
问题描述
我有用户输入一个字符串,然后检查一下它是否为双。如果它不是一个double,我抛出一个异常,我创建了
try {
price = Double.parseDouble(strPrice );
}
catch(NumberFormatException nfe){
CDException cde = new CDException();
cde.setMessage(Price must be a number,\\\
Cannot create CD);
throw cde;
}
在确定它是一个数字后,在我的其他类中我检查确保它在我想要的范围内。 (在这种情况下为非负)然后创建一个值为
的对象public void setPrice(double newPrice)throws Exception {
if(newPrice> = 0){
this.price = newPrice;
}
else {
CDException cde = new CDException();
cde.setMessage(CD价格不能为负,\\\
Cannot创建CD);
throw cde;
}
}
所以我的问题是...
有一种方法可以一步完成,检查用户是否输入了一个数字,并且该数字是非负数。另一件事是,如果输入为空,那就是结束输入循环的指令。
strong>可以将您的代码更改为:
try {
price = Double.parseDouble(strPrice );
if(price< 0){
throw new CDException(Can not be negative);
}
} catch(NumberFormatException ex){
...
}
但问题是你是否真的想这样做。从设计的角度来看,在 setPrice
中进行否定检查可能更有意义,而不是作为解析逻辑的一部分。
Im writing a program for homework where I need to validate user input and then create an object and add it to an array list. i have included just what i think is the relevant code, but im a beginner for sure so let me know if there is something else you need to see.
I have the user enter a string, then check to see if its a double. if its not a double, i throw an exception that i created
try{
price = Double.parseDouble(strPrice);
}
catch(NumberFormatException nfe){
CDException cde = new CDException();
cde.setMessage("Price must be a number,\nCannot create CD");
throw cde;
}
after making sure that it is a number, in my other class i check to make sure it is in the range that i want. (non negative in this case) then create an object with the value
public void setPrice(double newPrice)throws Exception{
if(newPrice >= 0){
this.price = newPrice;
}
else{
CDException cde = new CDException();
cde.setMessage("CD Price cannot be negative,\nCannot create CD");
throw cde;
}
}
so my question is...
is there a way to do this in one step, check both that the user entered a number and that the number is non negative. one other thing is that if the input is blank, that is the instruction to end the input loop.
Well, you could change your code to read:
try {
price = Double.parseDouble(strPrice);
if (price < 0) {
throw new CDException("Can't be negative");
}
} catch (NumberFormatException ex) {
...
}
But the question is whether you'd really like to do that. From a design perspective, it might make more sense to do the "negative" check inside setPrice
, rather than doing it as part of the parsing logic.
这篇关于Java:正确的方式来抛出并捕获异常以验证输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!