I am creating a matrix class in java, and the following is the method for adding two matrices.
public MyMatrix addMatrix(MyMatrix matB) {
// if (myR != matB.myR || myC != matB.myC) throw an exception
MyMatrix res = new MyMatrix("", myR, myC, 0.0);
for (int i = 0; i < myR; i++) {
for (int j = 0; j < myC; j++) {
res.myElements[i][j] = myElements[i][j] + matB.myElements[i][j];
}
}
return res;
}
myR is the number of rows and myC is the number of columns in the MyMatrix class.
I want to throw an exception if the number of rows or columns of two matrices are different.
How can I throw an exception in the simplest way possible, without having to create a custom exception or anything else?
I tried
if (myR != matB.myR || myC != matB.myC) throw new Exception();
but it didn’t work. Specifically, it is giving the error "main" java.lang.Error: Unresolved compilation problem: Unhandled exception type Exception".
>Solution :
use : IllegalArgumentException
is a Runtime exception
public MyMatrix addMatrix(MyMatrix matB) {
if (myR != matB.myR || myC != matB.myC) {
throw new IllegalArgumentException("Matrices must have the same number of rows and columns to be added.");
}
MyMatrix res = new MyMatrix("", myR, myC, 0.0);
for (int i = 0; i < myR; i++) {
for (int j = 0; j < myC; j++) {
res.myElements[i][j] = myElements[i][j] + matB.myElements[i][j];
}
}
return res;
}