如何设置我的try和catch块?

时间:2018-01-20 21:36:37

标签: java class exception try-catch

每个人我都是初学程序员,手上有点问题。我正在尝试为我的一个类创建一个项目的测试语句,并遇到了一个问题。我似乎无法尝试并抓住阻止工作。我已经尝试过使用超级和继承以及我能想到的一切,但我可​​以让它工作。我也不知道我是否正在测试我的课程。我很困惑如何设置一个尝试并抓住这个类,帮助会很好。非常感谢你提前。以下是我的代码:

 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());

    }
}

}

3 个答案:

答案 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}的主体),请尝试并捕获工作。如果没有例外,他们将无法工作。这就是他们的工作方式