我有方法時,各方都知道,它計算三角形的角度:Testng。如何處理這個異常正確
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;
}
計算算法是正確的。關於例外的問題。它必須扔在這裏。
如何正確處理此異常(在此使用throws
或try
/catch
或其他?)?或者更好地拋出它(但這種方法看起來不正確,在測試中包圍try
/catch
)?
@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));
}
你能幫我解決這個問題嗎?
用'throws TriangleTechnicalException'聲明它。當調用該方法時,如果可以做到這一點,就用'try' /'catch' **來處理**,或者如果你不能這樣做,只需在該方法中添加'TriangleTechnicalException'即可。只有當你知道如何處理它們時才捕捉異常(無論這意味着重試,記錄警告,中止程序,無論如何)。 – Blorgbeard
這取決於...你如何*希望*這種方法在這些條件下行爲。你是否希望它拋出異常?或者是其他東西?你如何*想要消耗代碼來處理它? – David
@Blorgbeard,我想處理這個異常的方法有這種方法 - 'calculateTriangleAngles'。當我用'calculateTriangleAngles'方法使用'throws'時,我想這對測試這種方法來說不是很好。 在試驗中'try' /'catch'是很好的做法嗎? –