Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

making an exception in java

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".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading