有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java 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;
}

计算算法正确。关于例外的问题。必须扔到这里

我如何正确处理这个异常(在这里使用throwstry/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));
}

你能帮我回答这个问题吗


共 (2) 个答案

  1. # 1 楼答案

    您需要将抛出添加到方法声明中

    public static double[] calculateTriangleAngles(double a, double b, double c) throws TriangleTechnicalException {
    

    然后,无论何时使用此方法,都需要在try块内执行此操作,或者让该方法也抛出Trianglete异常

  2. # 2 楼答案

    我的建议是声明calculateTriangleAngles抛出TriangleTechnicalException,即将第一行更改为

    public static double[] calculateTriangleAngles(double a, double b, double c) 
        throws TriangleTechnicalException {
    

    以便通知来电者有问题。我认为,这比在方法中处理错误并返回某种特殊值或(更糟的是)一个假定值以解决错误或类似问题要好得多

    如果我没记错的话,如果TriangleTechnicalExceptionRuntimeException的子类,那么调用方不必捕获异常;如果异常发生,它将冒泡,直到某个调用方捕获它,或者到达顶层,程序终止。所以测试用例不需要捕捉异常。但是,您肯定需要测试错误处理代码,在这种情况下,您需要捕获异常,以验证错误处理是否按预期工作