简体   繁体   中英

how to use throw exception in java

I have problems using try-catch in method inverse() , after running the code I get this error:

Exception TanpaInvers is never thrown in body of corresponding try statement

The code is like this:

class SalahIndex

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

class TanpaInverse

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

method class 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;
}

What the compiler is complaining about is that in your code you say by catch something like "when a TanpaInverse is thrown, do this", while your code will definitely not throw such an exception.

Instead, you should use throw our exceptions if sth. is going wrong with the matrix. Not knowing what Tanpa and Salah in your language mean, it's hard to say when they should be thrown, but sth. like this would seem right to me:

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

THis way, any method calling your inverse can/must have a try/catch block to handle possible exceptions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM