【问题标题】:difference between if throws and tryif throws 和 try 的区别
【发布时间】:2018-04-09 22:15:43
【问题描述】:

我一直在使用 Team Tree house 以及其他方法来学习 Java。好吧,在其中一个视频中,我们制作了一个使用 throw 异常的 IF 语句。没什么可疯狂的。问题是当我在它上面创作时,它仍然会抛出疯狂的长信息。只是为了澄清这里不谈论使用 try catch 只是使用 if 来引发异常。一个完美的例子是如果获得输入并想要检查输入是否为空白。如果它的空白抛出异常说它的空白。好吧,消息有效,我只是收到了很长的消息。那么我如何只收到我的消息?我已经编辑了帖子以包含下面的代码。下面的代码是一个简单的刽子手游戏。现在我完全理解了 try catch 方法是如何工作的,但是,当我在自己的程序中使用带有 throw 异常的 if 语句时,它会抛出整个丑陋的消息。当在这个程序上时,它只抛出自定义消息,如果你看你会发现它没有包含在 try catch 方法中。

package hangMan;
import java.util.Scanner;    

public class hangMan {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("What word would you like to guess? ");
        String guessWord = input.nextLine();
        for(int i = 0; i < 10; i++){
            System.out.println("");
        }

        //create objects for game and prompter class

        Game game = new Game(guessWord);
        Prompter prompter = new Prompter(game);

        while(game.getRemainingTries() > 0 && !game.isWon()){
        prompter.displayProgess();
        prompter.promptForGuess();
        }
        prompter.displayOutcome();
    }

}

package hangMan;

public class Game {
public static final int MAX_MISSES = 7;
private String answer;
private String hits;
private String misses;

//constructor set answer when created
public Game(String answer){
    this.answer = answer;
    hits = "";
    misses = "";


}

public void setAnswer(String answer){
    this.answer = answer;
}

public boolean applyGuess(String letters){
    if(letters.length()==0){
        throw new IllegalArgumentException("No leter found");
    }
    return applyGuess(letters.charAt(0));
}
private char normalizedGuess(char letter){
    if(! Character.isLetter(letter)){
        throw new IllegalArgumentException("Not a letter");
    }
    letter = Character.toLowerCase(letter);
    if(misses.indexOf(letter) != -1 || hits.indexOf(letter)!= -1){
        throw new IllegalArgumentException("You already guessed that letter");

    }

    return letter;
}

public String getAnswer (){
    return answer;
}

//apply guess method get letter to check with answer
public boolean applyGuess(char letter){
    letter = normalizedGuess(letter);
    //checks if letter is in answer
    boolean isHit = answer.indexOf(letter) != -1;
    //if it is store letter if not store letter in misses
    if(isHit){
        hits += letter;
    } else{
        misses += letter;
    }
    //return result hit or not
    return isHit;
}

public int getRemainingTries(){
    return MAX_MISSES - misses.length();
}
public String getCurrentProgress(){
    String progress = "";
    for (char letter : answer.toCharArray()){
        char display = '-';
        if(hits.indexOf(letter) != -1){
            display = letter;
        }
        progress += display;
    }
    return progress;
}

public boolean isWon(){
    return getCurrentProgress().indexOf('-') ==-1;
}

}


package hangMan;
import java.util.Scanner;

public class Prompter {
    private Game game;

    //constructor
    public Prompter(Game game){
        this.game = game;

    }

    public Prompter(String topic){

    }
    //prompt method to get input and send it to be tested
    public boolean promptForGuess(){
        boolean isHit = false;
        Scanner scanner = new Scanner(System.in);
        boolean isAcceptable = false;

        do{
        System.out.print("Enter a letter:  ");
        String guessInput = scanner.nextLine();

        try{
            isHit = game.applyGuess(guessInput);
            isAcceptable = true;
        }catch(IllegalArgumentException iae){
            System.out.printf("%s. Please Try again %n",iae.getMessage());
        }
        } while(! isAcceptable);
        return isHit;
    }

    public void displayOutcome(){
        if(game.isWon()){
            System.out.printf("Congrats you won with %d number of tries remaining!", game.getRemainingTries());
        }else{
            System.out.printf("Bummer the word was %s.  :(", game.getAnswer());
        }
    }

    public void displayProgess(){
        System.out.printf("You have %d remaining tries to guess: %s %n", game.getRemainingTries(), game.getCurrentProgress() );
    }

}

【问题讨论】:

  • 请提供您代码的一些相关sn-ps。
  • 您让异常气泡一直未处理到堆栈中 - 这会导致堆栈展开并退出线程。这就是你所看到的。在某些时候,您需要catch处理异常。

标签: java if-statement exception try-catch throw


【解决方案1】:

抛出异常与 try catch 不同。他们是相关的。但不一样。

抛出异常基本意思是:intentionally shows an exception (or error) within your code请参阅“异常”的定义here

同时,try-catch机制基本意思是:defining what to do when an exception shows up in your code


看下面这段代码:

public static anImportantFunction(String word) {
    ...
    if(word.length()==0){
        throw new IllegalArgumentException("No letter found");
    }
    ...
}

该代码表示​​I want this program to fail/error when the word submitted are empty。为什么我们会故意在代码中出错!? 这样我们就可以确保程序由于错误的实现而失败。这与在控制台中写入消息不同,因为在控制台中写入实际上不会停止我们的程序。

【讨论】:

  • 好的,那么这意味着执行此抛出异常的 if 语句必须引用代码中某处的 try catch 方法。因为它只显示自定义消息。我只是想确保我没有失去理智。所以只是为了澄清一下,为了避免“可怕的消息”大声笑,你需要使用 try catch 来处理异常,这样它就不会正确关闭程序?
  • 我并没有真正理解第一句话。对不起,语言障碍嘿嘿。但是,是的,我们可以使用 try-catch 来处理抛出的异常(特别是:告诉我们如果出现异常会做什么),这样我们就可以避免关闭程序的事情。
【解决方案2】:

如果您不希望异常消息与完整的堆栈跟踪一起出现,那么您需要使用try/catch 块捕获异常并使用异常变量仅打印出消息。特别是,您对给定异常的 getMessage() 方法感兴趣。

【讨论】:

    猜你喜欢
    • 2011-02-20
    • 2014-04-14
    • 2014-10-26
    • 2010-10-08
    • 2017-09-04
    • 2010-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多