无法更改异常中使用的 int

Unable to change an int used in exception

如果 fish.x 大于 500 我想将其重置为默认值 20:

private Fish addFish(String name, int x, int y) {
        Fish fish = new Fish(name, x, y);
        try {
            if (fish.getX() > 500) throw new Exception ("OutOfBounds");
            } catch (Exception e) {
                System.out.println("x > 500");
                fish.setX(20);
                fish.setY(20);
                System.out.println(fish.getX());
        }
        return fish;
    }

这个对Y值有效,但是x值不能改,怎么改?

解决方法是不抛出异常。

没有必要这样做,而且这样做真的没有意义,因为抛出异常意味着 您不打算在此方法中修复“异常”问题而是计划在调用方法中这样做,或者甚至在调用堆栈的更上层,即捕获异常的方法.

如果该方法需要检查 x 值并更改它,那么只需让它这样做而忘记抛出不需要的,在这种情况下,错误,异常:

private Fish addFish(String name, int x, int y) {
   if (x > 500) {
       x = 20;
       y = 20;
   }
   return new Fish(name, x, y);
}

或者这可能是您正在寻找的(如果 x 和 y 必须接受相同的限制):

private Fish addFish(String name, int x, int y) {
    x = x > 500 ? 20 : x;
    y = y > 500 ? 20 : y;
    
    return new Fish(name, x, y);
}

另一方面,如果这是一项学术作业并且需要某种例外,那么您将需要更多代码(和复杂性)来解决这个问题,可能类似于:

public class FishOutOfBoundsException extends Exception {
    public FishOutOfBoundsException(String message) {
        super(message);
    }
}

addFish 方法将被声明为抛出异常,除抛出异常外不应处理异常情况:

private Fish addFish(String name, int x, int y) throws FishOutOfBoundsException {
    if (x > MAX_X) {
        String text = String.format("X value of %d, greater than max X, %d", x, MAX_X);
        throw new FishOutOfBoundsException(text);
    }
    if (y > MAX_Y) {
        String text = String.format("Y value of %d, greater than max Y, %d", y, MAX_Y);
        throw new FishOutOfBoundsException(text);
    }
    return new Fish(name, x, y);
}

然后在调用代码中,将处理异常:

Fish myFish = null;
try {
    myFish = addFish("My Fish", someX, someY);
} catch (FishOutOfBoundsException foobe) {
    // some error message perhaps?
    myFish = addFish("My Fish", 20, 20);
}