自定义异常类正确处理异常

时间:2018-08-14 09:31:11

标签: java exception exception-handling

在我做的猜谜游戏中,我的代码需要具有两个自定义异常类(BadGuessExceptionTooManyGuessesException),每个类具有两个构造函数。猜谜游戏还需要具有try-catch-catch块并带有异常处理。

我的程序没有错误编译和正常运行,但是当我有意执行一些会引发异常的操作时,例如进行五次以上的回合操作(会引发TooManyGuessesException),而不是输出消息我希望该程序停止运行。对于如何正确输出错误消息的任何帮助,将不胜感激。

public class BadGuessException extends Exception
{
  /**
   * no-arg constructor
   */
  public BadGuessException()
  {
    super("Sorry, that was an invalid guess!");
  }

  /**
   * parametrized constructor
   * @param message String message passed to super class's constructor
   */
  public BadGuessException(String message)
  {
    super(message);
  }

  /**
   * getMessage method to return error message for exception
   */
  @Override
  public String getMessage()
  {
    return "Sorry, that was an invalid guess!\n" + 
           "Please enter a number between 1 and 10.";
  }
}

public class TooManyGuessesException extends Exception
{
  /**
   * no-arg constructor
   */
  public TooManyGuessesException()
  {
    super("Sorry, too many guesses!");
  }

  /**
   * parametrized constructor
   * @param guess integer value representing amount of guesses (turns)
   */
  public TooManyGuessesException(int guess)
  {
    super("Sorry, you guessed " + guess + " times!");
  }

  /**
   * getMessage method to return error message for exception
   */
  @Override
  public String getMessage()
  {
    return "Sorry, too many guesses!";
  }
}

import java.util.Random;
import java.util.*;

public class GuessingGame
{
  public static void main(String[] args)
  {
    //Scanner object to receive user input
    Scanner keyboard = new Scanner(System.in);

    //Create Random class object & random variable
    Random rng = new Random();
    int n = rng.nextInt(10 - 1 + 1) + 1;

    //Initialize incrementor for guessing turns
    int turn = 1;

    //Initialize variable for user input (guess)
    int guess = 0;

    try
    {
      do
      {
        //Exception handling for more than five turns
        if(turn > 5)
          throw new TooManyGuessesException();

        //Prompt user to enter their guess
        System.out.println("Guess a number between 1 and 10 inclusive.");
        System.out.println("Hint: the answer is " + n);
        //Receive user input (their guess)
        guess = keyboard.nextInt();

        //Exception handling for number guess
        if(guess == n)
          System.out.println("YOU WIN!\nIt took you " + turn + " attempts.");
        else if(guess < 1 || guess > 10)
          throw new BadGuessException();

        //Increment turn variable
        turn++;        
      }while(guess != n);
    }
    catch(BadGuessException | TooManyGuessesException e)
    {
      e.getMessage();
    }
    catch(NumberFormatException e)
    {
      System.out.println("Sorry, you entered an invalid number format.");
    }

  }
}

0 个答案:

没有答案
相关问题