我使用了一些异常,但即使抛出并捕获了一个异常,它也会在捕获块之后继续输出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!nn");
} 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!nn");
}
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);
}
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
实际上并不是throw
,而是Exception
。它打印并吞噬它。要调用上面的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!nn");
throw e; // <-- add this.
}
}