java - 在 Java 中抛出异常而不终止程序

标签 java exception

所以我有一个程序,我想检查一组绳索是否在游戏板内,如果不在,则抛出错误,但继续执行该程序。这是使用的代码(我不担心类/包名称):

package routines;

import java.util.Random;

import game.GameBoard;
import game.Player;

public class MovePlayer extends Routine {
final protected int destX;
final protected int destY;

public MovePlayer(int destX, int destY, GameBoard board) {
    super();
    if(destY > board.getHeight() || destX > board.getWidth()) {
        fail();
        throw new RuntimeException(">>> Error while creating routine, one or more coords are outside of the game board");
    } else {
        this.destX = destX;
        this.destY = destY;
    }
}

这里是父类(super class)的链接(很多代码,不确定我是否应该把所有的都放在这里)Super class SRC

编辑:不确定这是否会解决我想要的问题,但我所做的只是从变量中删除 final 关键字

编辑#2:所以我终于明白我做错了什么。 1)变量被标记为最终的。 2) 是我的一些其他代码导致了这种情况发生*facepalm* 我所有的代码都被推送到一个新的 Git 存储库中,所以如果你应该选择,你可以看看是什么我在这里做的:VI-Arena Git repository

最佳答案

我想出了我需要做什么以及如何做。如果满足条件,我需要停止创建例程对象,这是通过抛出错误来完成的。已经完成了,但我错误地在 try...catch block 中设置了变量。因此,如果条件不满足,它就会失败并停止,如果条件满足,它会创建对象并在 try...catch block 的外部设置变量,这是有效的。我的新代码如下:

package routines;

import java.io.IOException;
import java.util.Random;

import game.*;

public class MovePlayer extends Routine {

    private final int destX;
    private final int destY;
    private final Random random = new Random();

    public MovePlayer(int destX, int destY, GameBoard board) throws IOException {
        super();
        try {
            if (destY > board.getHeight() || destX > board.getWidth()) {
                throw new IllegalArgumentException(">>> Error while creating routine, one or more coords are outside of the game board");
            } else {
            }
        } catch (IllegalArgumentException e) {
            fail();
        System.err.println(e.getLocalizedMessage());
    }
    this.destX = destX;
    this.destY = destY;
}

关于java - 在 Java 中抛出异常而不终止程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32081044/

相关文章:

java - 如何更改数据透视表中的默认标题背景颜色

java - 无法使 GWT devmode 插件与 Firefox 一起使用

java - 检查 map 的空值

.net - System.DirectoryServices 中的间歇性异常

exception - Dart:没有异常的消息规范?

java - 如何使用java正则表达式正确替换字符串中的字符?

java - 使用凯撒密码和给定方法进行加密..Java

java - 当构造函数可能抛出受检查异常时如何实现 Singleton

python - Python : Handling requests exceptions the right way

asp.net-mvc - Entity Framework 中的异常处理,具有存储库模式的 MVC