如何捕获illegalargumentexception而不是终止?

smdnsysy  于 2021-07-03  发布在  Java
关注(0)|答案(2)|浏览(403)

我正在尝试完成一个项目,在这个项目中,我必须在我的程序中捕获一个非法的argumentexception。它正确地抛出异常,但是当它抛出异常时,程序终止,而不是运行catch并继续。不知道怎么了,我试过几种不同的方法。
以下是我的主要观点:

import java.util.Scanner;

public class MonthDaysTest 
{
  public static void main(String[] args) 
  {
    int month = 1, year = 2020;
    boolean tryAgain = true; //exception thrown test variable
    Scanner input = new Scanner(System.in);

    //repeats attempt for input until an exception is not thrown
    do
    {
        try
        {
            //prompts for int representing the month
            System.out.print ("Enter the month (1=January, 2=February, ..., 12=December): ");
            month = input.nextInt();

            //prompts for int representing the year
            System.out.print ("Enter the year: ");
            year = input.nextInt();

            //sets the test variable to false if an exception is not thrown
            tryAgain = false;
        }
        catch (IllegalArgumentException illegal)
        {                              
            input.nextLine(); //discards input so user can try again
            System.out.printf("Exception: %s%n%n", illegal.getMessage());
        }
    }
    while (tryAgain);

    MonthDays monthDay = new MonthDays(month, year);

    //prints out message with number of days in requested month
    System.out.printf ("%d%s%d%s%d%s", monthDay.getMonth(), "/", monthDay.getYear(), " has ", monthDay.getNumberOfDays(), " days.");
  }
}

以及我的monthdays课程的相关部分:

public class MonthDays
{
  private int month, year;

  //constructor for class
  public MonthDays(int month, int year)
  {
    setMonth(month);
    setYear(year);
  }                                  

  //sets the month while making sure it is valid
  public void setMonth(int month)
  {
    if (month < 1 || month > 12)
    {
      throw new IllegalArgumentException("Month must be between 1 and 12.");
    }
    this.month = month;
  }

  //sets the year while making sure it is valid in that it is after the implementation of the Gregorian calendar
  public void setYear(int year)
  {
    if (year < 1583)
    {
      throw new IllegalArgumentException("Year must be 1583 or later.");
    }
    this.year = year;
  }
}

当我用非法的月份输入运行程序时,我得到的是:

Exception in thread "main" java.lang.IllegalArgumentException: Month must be between 1 and 12.
    at monthDaysTest.MonthDays.setMonth(MonthDays.java:24)
    at monthDaysTest.MonthDays.<init>(MonthDays.java:15)
    at monthDaysTest.MonthDaysTest.main(MonthDaysTest.java:73)
C:\Users\jolen\AppData\Local\NetBeans\Cache\9.0\executor-snippets\run.xml:111: The following error occurred while executing this line:
C:\Users\jolen\AppData\Local\NetBeans\Cache\9.0\executor-snippets\run.xml:94: Java returned: 1
BUILD FAILED (total time: 3 seconds)

我发现另一个问题问了一些类似的问题,但我看不出我所做的与那个问题的答案有什么不同。就在这里:抓住非法辩论例外?

ax6ht2ek

ax6ht2ek1#

在要调用的构造函数中,可以通过异常调用方法:

public MonthDays(int month, int year)
  {
    setMonth(month);
    setYear(year);
  }

您还需要将构造函数调用放在try-catch块中:

MonthDays monthDay = new MonthDays(month, year);

比如:

MonthDays monthDay;
do
{
    try
    {
        //prompts for int representing the month
        System.out.print ("Enter the month (1=January, 2=February, ..., 12=December): ");
        month = input.nextInt();

        //prompts for int representing the year
        System.out.print ("Enter the year: ");
        year = input.nextInt();
        monthDay  = new MonthDays(month, year)

        //sets the test variable to false if an exception is not thrown
        tryAgain = false;
    }
    catch (IllegalArgumentException illegal)
    {                              
        input.nextLine(); //discards input so user can try again
        System.out.printf("Exception: %s%n%n", illegal.getMessage());
    }
}
while (tryAgain);
30byixjq

30byixjq2#

抛出异常的代码需要在try-catch块中才能被捕获。对你来说 new MonthDays(month, year); 抛出异常。你应该把 MonthDays monthDay = new MonthDays(month, year); 行至前 tryAgain = false; 声明。

相关问题