如何在java中抛出异常?

时间:2011-12-08 18:10:47

标签: java exception

嗯..这是给我的指示:

  

支持添加&与其他Money对象的减法
  如果货币不兼容,则抛出异常。

嗯..我已经有了一个带有add()的钱类。在这种情况下,我究竟如何抛出异常?我的意思是,我知道怎么做try {} catch但我应该去哪里做?我是否在同一个班级上这样做?或者是否应该在main()中进行异常抛出,其中发生所有其他事情?

public class Money {

    Currency currency;
    int dollar;
    int cents;

    //constructor
    public Money(Currency currency, int dollar, int cents) {
        super();
        this.currency = currency;
        this.dollar = dollar;
        this.cents = cents;
    }
    .
    .
    .
    .
    public Money add(Money moneyToBeAdded){
        Money result = new Money(moneyToBeAdded.getCurrency(),0,0);
        Money totalInCents;

        if(compareCurrency(moneyToBeAdded)){
            totalInCents = new Money(moneyToBeAdded.getCurrency(),0,(moneyToBeAdded.toCents() + cents));
            result = totalInCents.toDollars();
        }//to do convert currency

        return result;
    }

    public Money subtract()

    public boolean compareCurrency(Money money){
        return money.currency.equals(currency);
    }
}

6 个答案:

答案 0 :(得分:4)

throw new Exception("Currencies are incompatible");

但是,我会考虑创建一个app或Money特定的异常,根据您的需要对ExceptionRuntimeException进行子类化。

如果事情必须是精细的,那么MoneyConversionException可能会延长MoneyException

答案 1 :(得分:2)

我认为这是使用未经检查的异常的好地方;任何添加不兼容的钱的尝试都是由编程错误引起的。所以我建议:

if (!compareCurrency(moneyToBeAdded))
  throw new IllegalArgumentException("Mismatched currencies.");

由于IllegalArgumentException派生自RuntimeException,因此您无需声明add()方法可以抛出它。

创建RuntimeException的自定义子类。当应用程序尝试从特定错误中恢复时,自定义异常类型很有用,而不是仅使用相同的日志记录或警报机制来处理每个异常。程序不应该尝试从这样的特定编程错误中恢复。

答案 2 :(得分:1)

正如其他人所提到的,您可以随意使用大量资源(例如this)。无论如何,除此之外,我要警惕抛出自定义异常。相反,抛出现有的(例如IllegalArgumentException)以便最小化复杂性。

答案 3 :(得分:0)

一个应该抛出任何Exception的方法需要一个throw子句:

public Money add(Money moneyToBeAdded) throws MoneyException{..}

在该方法中,您需要过滤掉要抛出异常的情况(例如if-clauses),然后转到:

throw new MoneyException("don't like that currency");

在此示例中,MoneyException是一个扩展Exception的类:

class MoneyException extends Exception {..}

答案 4 :(得分:0)

答案 5 :(得分:0)

抛出异常是关于报告错误,并且必须将其声明为方法声明的一部分。例如:

class SomeMoneyProblem extends Exception {
      public SomeMoneyProblem() {
            super();
      }

      public SomeMoneyProblem(String msg) {
            super(msg);
      }
}

    public class Money {

       ...

       public Money() { 

       }

       public Money someMoneyMethod(Money moreMoney) throws SomeMoneyProblem {
               ....
               if ( someProblemCondition )
                      throw new SomeMoneyProblem();

               if ( someOtherProblem ) 
                      throw new SomeMoneyProblem("Other Problem");

       }

       public static void main() {

               Money m = new Money();
               try {
                    m.someMoneyMethod();
               } catch (SomeMoneyProblem p) {
                    System.err.println(p);
               }
       }
    }
相关问题