public Resistor (double resistancevalue, double tolerancevalue, double powerrating)throws Exception {
if (resistancevalue <= 0){
throw new Exception ("The resistance value must be greater than zero.");
}
if (tolerancevalue <=0 || tolerancevalue>=1){
throw new Exception ("The tolerance value must be between zero and one (not incusive).");
}
if (powerrating >=0){
throw new Exception("The power rating must be greater than zero.");
}
else{
this.resistancevalue=resistancevalue;
this.tolerancevalue = tolerancevalue;
this.powerrating = powerrating;
}
}
public double getResistanceValue(){
return resistancevalue;
}
double miniResistance(){
double Minir = resistancevalue*(1.0-tolerancevalue);
return Minir;
}
double maxResistance(){
double Maxr= resistancevalue*(1.0+tolerancevalue);
return Maxr;
}
测试类:
public static void main(String[] args) {
// TODO code application logic here
//Tesing the resistor class
//testing to see if the expection is caught when the resistence value is less than 0
double tolerancevalue = 0.5;
double powerrating = 1;
try {
double resistancevalue=1;
System.out.println("Exception Failed");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
答案 0 :(得分:1)
您尚未对Resistor
构造函数进行任何实际调用。以下代码按预期运行:
try {
double resistancevalue=1;
// the following line will throw an exception...
Resistor r = new Resistor(resistancevalue, tolerancevalue, powerrating);
System.out.println("Exception Failed");
} catch (Exception e) {
// the exception is caught and printed here
System.out.println(e.getMessage());
}
// prints "The power rating must be greater than zero."
答案 1 :(得分:1)
您需要在try-catch语句中调用Resistor构造函数。
public static void main(String[] args) {
// TODO code application logic here
//Tesing the resistor class
//testing to see if the expection is caught when the resistence value is less than 0
double tolerancevalue = 0.5;
double powerrating = 1;
try {
double resistancevalue=1;
Resistor testResistor = new Resistor(resistancevalue,tolerancevalue, powerrating);
System.out.println("Exception Failed");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
答案 2 :(得分:0)
如果程序中存在异常(尝试{here}的主体),请尝试并捕获工作。如果没有例外,他们将无法工作。这就是他们的工作方式