如何在java中使用throw异常

时间:2015-09-16 09:01:09

标签: java

我在方法inverse()中使用try-catch时遇到问题,运行代码后出现此错误:

  

异常TanpaInvers永远不会在相应的try的主体中抛出   声明

代码是这样的:

类SalahIndex

public class SalahIndeks extends Exception {
    public SalahIndeks(String pesan) {
        super(pesan);
    }
}

类TanpaInverse

public class TanpaInverse extends Exception {
    public TanpaInverse(String pesan) {
        super(pesan);
    }
}

方法类Matrix2x2

    double determinan(){
    int a11 = 0, a12 = 0, a21 = 0, a22 = 0;

    double determinan = this.a11 * this.a22 - this.a12 * this.a21;
    return determinan;
}

Matriks2x2 inverse() throws TanpaInverse, SalahIndeks {

    Matriks2x2 A = new Matriks2x2(a11, a12, a21, a22);
    double detA = A.determinan();

    if (detA != 0){
        try{
            double a11 = this.a22/detA;
            double a12 =  -this.a12/detA; 
            double a21 =  -this.a21/detA;
            double a22 =  this.a11/detA;

        }
        catch(TanpaInverse errT){}    
        catch(SalahIndeks e){}
    }

    return new Matriks2x2(a11, a12, a21, a22);
}
private int a11, a12, a21, a22;
}

1 个答案:

答案 0 :(得分:3)

编译器抱怨的是,在你的代码中,你通过catch说“当抛出TanpaInverse时,执行此操作”,而你的代码肯定不会抛出这样的异常。

相反,你应该使用抛出我们的异常,如果......矩阵出错了。不知道Tanpa和Salah用你的语言是什么意思,很难说什么时候应该被抛出,但是......这样对我来说似乎是正确的:

// here goes code for "if some condition is violated, throw a new SalahIndeks

if (detA != 0){

         double a11 = this.a22/detA;
         double a12 =  -this.a12/detA; 
         double a21 =  -this.a21/detA;
         double a22 =  this.a11/detA;

} else {
  throw new TanpaInverse();
}

这样,调用inverse的任何方法都可以/必须有try/catch块来处理可能的例外。