Java:捕获Driver类中Worker类抛出的异常

标签 java exception

我正在做家庭作业 (Hangman)。它已经完成,但我需要添加一个异常(exception)并且遇到困难。明天到期,但我仍然没有收到导师的消息,所以我想我会在继续等待的同时在这里发帖。作业要求:

public boolean guessCharacter(char guess) throws Exception - This method returns whether a given character is a part of the key phrase. If the guessed character is valid, then this method should return true, false otherwise. You should throw an exception if the guess has been guessed before (which can be taken care of by the code that is calling this method).

我假设我需要在工作类方法中抛出异常并在调用该方法的工作类中处理它。我搜索了 SO 并发现了这个:

Keep a reference to your workers in your GUI and in your workes add a try catch. In the catch assign the exception to a variable and add a getter to it. IN your GUI, when your worker is done, just check if there is an exception in the worker or not.

这看起来像我需要做的,但我不确定如何实现它。我想要一个代码示例。这是我目前所拥有的(guessedLetters 是一组):

public boolean guessCharacter(char guess) throws Exception
{   
    // Reset index
    if (index == keyPhrase.length())
        index = 0;

    // Determine if guessed letter is part of word
    if (guess == keyPhrase.charAt(index))
    {
        isValid = true;
        boardArray[index] = guess;  // If it is, place it correctly in array
        try {
            // SOME TYPE a = guessedLetters.add(Character.toString(guess));
        } catch (Exception e) {
        //  a = not sure what to do here;
        }
    } else
        isValid = false;

    index++;

    return isValid;
} 

应该注意的是,我根据单词的长度多次调用此方法,以检查用户对单词中每个字母的猜测。我敢肯定有一种更优雅的方式,我只是还没有想出一个。我也不确定对驱动程序类中的 boolean 结果有什么用处。

提前致谢!

最佳答案

您不应该在尝试的地方捕获异常,而应该抛出异常。

由于这是家庭作业,因此这是指导而非实际代码:

首先,检查集合以查看字母是否已被猜出。如果它已经存在于集合中,则抛出异常(throw new Exception("That letter has already been guessed!")。否则,将该字母添加到集合中,并照常继续。

如您的作业所述,此异常将“由调用此方法的代码处理”。在您演示的 guessCharacter 方法中,您只需在需要时抛出适当的异常(由于重复猜测)。

关于Java:捕获Driver类中Worker类抛出的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15049153/

相关文章:

java - 如何永久解决 Jenkins 中显示范围报告的 HTML Publisher 插件问题?

java - 如何使工作簿(输出流)将所有行写入 xlsx 文件而不是仅一行?

java - 在 hibernate 中动态添加查询字符串中的表名

java - 什么时候在代码中捕获 RuntimeExceptions?

c++ - 如果文件为空,如何在 C++ 中抛出异常?

javascript - 获取哪个函数/行在 javascript 中抛出异常

java - Java 中未知的 NullPointerException

java - 在一个巨大的集合中找到两个字符串的所有串联

python - C 中的参数处理错误 : "Expected " + str(status) + "got " + str(child. returncode))"

c++ - 在递归 C++ 函数中捕获 "Stack Overflow"异常