如何处理给定的自定义异常?

时间:2017-03-10 22:33:55

标签: java

我有一个Exception类,必须在我的编码中使用。我无法在构造时显示异常类包含的消息。这是给定的异常类。

public class MonthException extends Exception
{
    public MonthException()
    {
        super("Invalid value for month.");
    }

    public MonthException(String message)
    {
        super(message);
    }

    public MonthException(int month)
    {
        super("\n" + month + " is an invalid month number.");
    }
}

到目前为止,我已经编写了以下代码:

try
{
     String[] date = args[0].split("/");
     String month = date[0];
     String day = date[1];
     MonthException exception = new MonthException();
    if (Integer.parseInt(date[0]) < 1 || Integer.parseInt(date[0]) > 12)
    {
        throw new MonthException();
    }
    catch(MonthException exception)
    {
        System.out.println(MonthException.getMessage());
    } 
} 

4 个答案:

答案 0 :(得分:1)

try
{
    String[] date = args[0].split("/");
    String month = date[0];
    String day = date[1];
    //This is no need
    //MonthException exception = new MonthException();
    if (Integer.parseInt(date[0]) < 1 || Integer.parseInt(date[0]) > 12)
    {
        throw new MonthException(Integer.parseInt(date[0]));
    }
    catch(MonthException exception)
    {
        System.out.println(exception.getMessage());
    } 
} 

试试这个

答案 1 :(得分:0)

尝试: ...

catch(Exception e)
    {
        System.out.println(e.getMessage());
    }
...

答案 2 :(得分:0)

如果您定义了自己的 MonthException ,那么只要发生无效事件就抛出它,这将传播异常,该异常必须由调用方法重新抛出或捕获它

示例:

class MyException extends Exception{}

class Test{
    public void getMonatPayment(int index) throws MyException {
        if(index < 0){
             throw new MyException("Some msg");
        }
    }
}

class MainImplementation{
    public static void main(String[] args){
         Test t = new Test();
         try{
             t.getMonatPayment(-5);
          } catch(MyException ex){ //dosomething usefull}
    }
}

    public static void main(String[] args) throws MyException{
         Test t = new Test();
             t.getMonatPayment(-5);
    }

答案 3 :(得分:0)

你在那里写的是绝对没有意义。在try-catch-block中抛出异常应该是什么意思?因此,如果您甚至不了解面向对象的编程并执行以下操作,请不要使用例外情况:

int month = Integer.parseInt(date[0]);
if (month < 1 || month > 12) {
    System.out.println(month + " is not a valid month");
    return;
}

然而,这是您使用例外的方式:

public static int getMonth(String str) throws InvalidMonthException {
    int month = Integer.parseInt(str);
    if (month < 1 || month > 12) {
        throw new InvalidMonthException(month);
    }
    return month;
}

然后在方法中:

int month;
try {
    month = getMonth(date[0]);
} catch (InvalidMonthException e) {
    System.out.println(e.getMessage);
    return;
}
System.out.println(month); // Or whatever you want to do with your month.........