有 Java 编程相关的问题?

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

Java异常,捕获后,它仍然打印后面的内容

我使用了一些异常,但即使抛出并捕获了一个异常,它也会在catch块之后继续输出whats

我希望抛出的异常被捕获,并且只打印出捕获正文中的内容,除非没有异常并转到最后一个souf

然而,不知何故,当我有一个例外,我的渔获体是打印的,但它后面的souf也不应该打印

如何组织这些异常

----引发异常的方法

   public double getHeight() throws ExceptionCheck {
        //if end point is not set, return -1 (error)
        if(points[1] == null){
            throw new ExceptionCheck("The height cannot be calculated, the end point is missing!\n\n");
        } else {
            double height = points[1].getY() - points[0].getY();
            return height;
        }
    }

------处理从getHeight抛出的方法

@Override
public double getArea() {
    //if end point is not set, return -1 (error)

    double area = 0;

    try {
        area = getHeight() * getWidth();
    }
    catch(ExceptionCheck e){
        System.out.printf("The area cannot be calculated, the end point is missing!\n\n");
    }

    return area;
}

------这里不应打印捕获后的最后一个SOUF,但无论如何都要打印

private static void printArea(Shape shape) {
    System.out.println("Printing area of a " + shape.getClass().getSimpleName());

    double area = 0d;
    // Get area of the shape and print it.
    try {
        area = shape.getArea();
    }
    catch(ExceptionCheck e){
        System.out.printf(e.getMessage());
    }
   System.out.println("The area is: " + area);
}

共 (1) 个答案

  1. # 1 楼答案

    这不是catch的工作方式。如果在出现异常时不应打印,则必须将其移动到try的主体中。像

    // Get area of the shape and print it.
    try {
        double area = shape.getArea();
        System.out.println("The area is: " + area); // <  if the previous line throws
                                                    // an exception, this will not print.
    }
    catch(ExceptionCheck e){
        System.out.printf(e.getMessage());
    }
    

    你的方法getArea实际上并不throwException。它打印并吞下它。要调用上述catch,还必须修改getArea如下

    @Override
    public double getArea() throws ExceptionCheck {
        try {
            return getHeight() * getWidth();
        }
        catch(ExceptionCheck e){
            System.out.printf("The area cannot be calculated, the end point is missing!\n\n");
            throw e; // <  add this.
        }
    }