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 楼答案
这不是
catch
的工作方式。如果在出现异常时不应打印,则必须将其移动到try
的主体中。像你的方法
getArea
实际上并不throw
是Exception
。它打印并吞下它。要调用上述catch
,还必须修改getArea
如下