Reputation: 485
I have the method which calculates angles of the triangle when all sides are known:
public static double[] calculateTriangleAngles(double a, double b, double c) {
if (a <= 0 || b <= 0 || c <= 0 || a >= b + c || b >= a + c || c >= a + b) {
throw new TriangleTechnicalException("Incorrect side value");
}
double[] angles = new double[3];
angles[0] = round(Math.toDegrees(Math.acos((pow(b, 2) + pow(c, 2) - pow(a, 2)) / (2 * b * c))), 2);
angles[1] = round(Math.toDegrees(Math.acos((pow(a, 2) + pow(c, 2) - pow(b, 2)) / (2 * a * c))), 2);
angles[2] = round(Math.toDegrees(Math.acos((pow(a, 2) + pow(b, 2) - pow(c, 2)) / (2 * a * b))), 2);
return angles;
}
Calculation algorithm is correct. Question about exception. It must be thrown here.
How can I handle this exception correctly (use throws
or try
/catch
right here or something else?)? Or maybe better throws it (but this method can look not correctly, surrounded try
/catch
in tests)?
@Test
public void testCalculateTriangleAnglesTrue() {
double[] expResult = {48.19, 58.41, 73.4};
double[] result = new double[3];
try {
result = TriangleFunctional.calculateTriangleAngles(7, 8, 9);
} catch (TriangleTechnicalException e) {
fail();
}
assertTrue(Arrays.equals(expResult, result));
}
Can you help me with this question?
Upvotes: 0
Views: 539
Reputation: 17576
My advice is to declare that calculateTriangleAngles
throws TriangleTechnicalException
, i.e. change first line to
public static double[] calculateTriangleAngles(double a, double b, double c)
throws TriangleTechnicalException {
so that the caller is informed that there is a problem. This is, I believe, much better than handling the error within the method and returning some kind of special value or (even worse) a value which assumes values to resolve the error or something like that.
If I remember correctly, if TriangleTechnicalException
is a subclass of RuntimeException
then callers don't have to catch the exception; if the exception occurs, it will bubble up until some caller catches it, or it reaches the top level and the program terminates. So test cases need not catch the exception. But you will certainly want to test the error-handling code, in which case you will want to catch the exception, to verify that the error handling works as expected.
Upvotes: 1
Reputation: 64
You need to add throws to your method declaration.
public static double[] calculateTriangleAngles(double a, double b, double c) throws TriangleTechnicalException {
Then whenever you use this method, you need to either do so inside of a try block, or have that method also throw the TriangleTechnicalException
Upvotes: 1