Unable to change an int used in exception

Solution 1:

The solution is not to throw an exception.

There's no need to do this, and it doesn't really make sense to do this since throwing an exception means that you're not planning to fix an "exceptional" problem here in this method but rather plan to do so in the calling method, or even further up the calling stack, the method that would be catching the exception.

If the method needs to check the x value and change it, then simply have it do that and forget about throwing unneeded, and in this situation, erroneous, exceptions:

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

or perhaps this may be what you're looking for (if both x and y must undergo the same restrictions):

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

On the other hand, if this is an academic assignment and an exception of some sort is required, then you will need more code (and complexity) to solve this, perhaps something like:

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

The addFish method would be declared to throw the exception and should not handle the exceptional situation other than to throw the exception:

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

And in then in the calling code, one would handle the exception:

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