【问题标题】:Custom exceptions not working自定义异常不起作用
【发布时间】:2014-04-11 02:33:50
【问题描述】:

我正在尝试创建两个异常,一个在月份编号大于 12 或小于 1 时抛出,另一个在月份名称无效时抛出。我以为我包含了所有必要的步骤(我不擅长例外),但我的主课仍然无法正常工作。关于我做错了什么的任何见解?

public class Month {
private int monthNumber;

/**
 * Creates a new month set to January
 */
public Month(){
    monthNumber = 1;
}

/**
 * Creates a month set to the month number provided by the user
 * @param m the number of the month
 */
public Month(int m) throws MonthsNumberException{
    if (m<1 || m>12){
       throw new MonthsNumberException("Number has to be greater than 1 and less than 12");
    }else{
        monthNumber = m;
    }
}

/**
 * Creates a month based on the string name provided
 * @param m String values for the name of the month
 */
public Month(String m) throws MonthsNameException{
    switch(m){
        case "January":
            monthNumber = 1;
            break;
        case "February":
            monthNumber = 2;
            break;
        case "March":
            monthNumber = 3;
            break;
        case "April":
            monthNumber = 4;
            break;
        case "May":
            monthNumber = 5;
            break;
        case "June":
            monthNumber = 6;
            break;
        case "July":
            monthNumber = 7;
            break;
        case "August": 
            monthNumber = 8;
            break;
        case "September":
            monthNumber = 9;
            break;
        case "October":
            monthNumber = 10;
            break;
        case "November":
            monthNumber = 11;
            break;
        case "December":
            monthNumber = 12;
            break;
                default:
    throw new MonthsNameException("Invalid month name: " + m);
    }
}

/**
 * changes the month to the number provided
 * @param m the number of the month
 */
public void setMonthNumber(int m) throws MonthsNumberException{
    if (m<1 || m>12){
        throw new MonthsNumberException("Number has to be greater than 1 and less than 12");

    }else{
        monthNumber = m;
    }
}

/**
 * returns the number of the month
 * @return the number of the month
 */
public int getMonthNumber(){
    return monthNumber;
}

/**
 * returns the name of the month
 * @return the name of the month
 */
public String getMonthName(){
    String month="";

    switch(monthNumber){
        case 1:
            month = "January";
            break;
        case 2:
            month = "February";
            break;
        case 3:
            month = "March";
            break;
        case 4:
            month = "April";
            break;
        case 5:
            month = "May";
            break;
        case 6:
            month = "June";
            break;
        case 7:
            month = "July";
            break;
        case 8:
            month = "August";
            break;
        case 9:
            month = "September";
            break;
        case 10:
            month = "October";
            break;
        case 11:
            month = "November";
            break;
        case 12:
            month = "December";
            break;

    }
    return month;
}

/**
 * returns a string representation of the month
 * @return the name of the month
 */
public String toString(){
    return getMonthName();
}

/**
 * if the two items are the same returns true
 * @param m the month object to compare
 * @return true if they are the same, false if not
 */
public boolean equals(Month m){
    if (m.getMonthNumber() == this.getMonthNumber()){
        return true;
    }else{
        return false;
    }
}

/**
 * If this calling item is after the month object passed as argument returns true
 * @param m the month object
 * @return true if calling object greater, false of argument greater
 */
public boolean greaterThan(Month m){
    if (this.getMonthNumber()>m.getMonthNumber()){
        return true;
    }else{
        return false;
    }
}

/**
 * If this calling item is before the month object passed as argument returns true
 * @param m the month object
 * @return true if calling object less than, false of argument less than
 */
public boolean lessThan(Month m){
    if (this.getMonthNumber()<m.getMonthNumber()){
        return true;
    }else{
        return false;
    }
}
class MonthsNumberException extends Exception
{
    public MonthsNumberException(String message)
    {
        super(message);
    }
}
class MonthsNameException extends Exception
{
    public MonthsNameException(String message)
    {
        super(message);
    }
}

}

import javax.swing.*;

public class MonthDemo {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    String response = JOptionPane.showInputDialog(null, "Please enter a month number");
    int mNumber = Integer.parseInt(response);

    Month m1 = new Month(mNumber);

    JOptionPane.showMessageDialog(null, m1.toString());

    response = JOptionPane.showInputDialog(null, "Please enter a month name");
    Month m2 = new Month(response);
    JOptionPane.showMessageDialog(null, m2.toString());

}

}

【问题讨论】:

  • 你必须定义“不工作”
  • 关于错误是什么的任何提示?错误信息?堆栈跟踪?一种行为?
  • 您能告诉我们确切哪些错误吗?
  • @user2288575 因此,您尚未向我们展示的方法中的一行代码会为您提供一条“弯曲的红线”。我 1988 年的 vi 副本没有显示弯曲的红线,所以我不知道你在说什么。也许你有一个新奇的 IDES,问题是那个 IDE 中波浪形的红线是什么意思?
  • @user2288575 你不能尝试一个更简单的程序来确保你真正理解如何至少以基本的方式使用异常吗?而且,我根本无法理解为什么你不能简单地给出你所面临的错误信息。为什么有人需要复制您的代码并自己找出来?

标签: java exception throw


【解决方案1】:

问题 #1:您必须在更改月份时抛出异常。

问题 #2:不允许在 Main 中捕获异常 方法。

在完全了解您的作业后,我为您提供了一个简短的解决方案。当您扩展 Exception 时,这称为“已检查”异常,这意味着您必须将其包围在 try catch 中,但是如果您扩展 RuntimeException(also Error),它将允许您在主线程中执行该方法而无需处理它。这样做的结果是如果抛出异常,您的程序将关闭,但这似乎是您作业的预期结果。将您的代码与原始问题中的代码保持一致,然后进行更改。

@SuppressWarnings("serial")
class MonthsNumberException extends RuntimeException {
    public MonthsNumberException(String message) {
        super(message);
    }
}

@SuppressWarnings("serial")
class MonthsNameException extends RuntimeException {
    public MonthsNameException(String message) {
        super(message);
    }
}

这应该可以解决你的作业问题。

【讨论】:

  • 我其实是不允许改main方法的,只能改类。抱歉浪费您的时间 CodeCamper
  • @user2288575 您将继续收到该错误,直到您在 Main 方法中放置一个 try catch,因为您现在在它正在访问的方法中抛出异常。要么删除异常抛出,要么在 main 中放置 try catch。
  • 感谢 CodeCamper 的回复。 “然后,您将更改 Month 类以在可以更改月份编号的任何地方抛出该异常”这就是说明所说的内容。我需要在我的类中删除哪些异常抛出,因为我无法更改 main 方法。
  • @user2288575 任何抛出异常的方法都必须包含在 try catch 中。所以你不能在不添加 try catch 的情况下添加异常(例如在你的 Main 方法中)。我编辑了我的答案,向您展示如何抛出异常,然后在同一个方法中捕获它。有点像装满一桶水只是为了倒在地上。除非我们在这里缺少一些非常基本的东西,否则如果不更改 Main 方法,您的作业就无法明智地完成。
  • 这正是我想要的,谢谢。现在我需要能够用月份名称来做同样的事情,但它不允许我将该代码的整个部分放在“try”部分。
【解决方案2】:

没有试过你的代码,因为你没有告诉我们确切的错误,我只是在这里猜测。

您提到Month m2 = new Month(response); 行有问题。

Month(int) 构造函数正在抛出一个检查异常。但是,作为此构造函数的调用者的 main 方法没有进行任何适当的处理。您应该catch 它,或者将您的主要方法声明为throws MonthsNumberException


请不要像这样简单地扔掉一大段代码并“问”问题。你应该做很多事情:

  1. 有一个简化的程序来验证您的理解,并展示您的问题。 lessThan 方法与问题有何关系?您应该从您的问题中删除所有这些“噪音”,以便人们可以专注于您的问题

  2. 您应该提供足够的信息。如果有错误,请告诉我们错误消息或问题症状。仅仅丢掉一大段代码是没有用的。

【讨论】:

    猜你喜欢
    • 2013-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多