简体   繁体   中英

How do I throw an exception in java?

Hmm.. Here is the instruction given to me:

Supports addition & subtraction with other Money object
Throws exception if currencies are incompatible.

Hmm.. I already got a money class with add() in it. How exactly do I throw an exception in this case? I mean, I know how to do try{} catch but where am I supposed to do it? Do I do it on the same money class? or should the throwing of exceptions be done somewhere like in the main() where all other stuff takes place?

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);
    }
}
throw new Exception("Currencies are incompatible");

However, I'd consider creating an app- or Money -specific exception instead, subclassing either Exception or RuntimeException depending on your needs.

Perhaps a MoneyConversionException extending MoneyException if things have to be granular.

I think this is a good place to use an unchecked exception; any attempt to add incompatible monies is due to a programming error. So I'd suggest:

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

Since IllegalArgumentException derives from RuntimeException , you don't need to declare that the add() method can throw it.

Do not create a custom subclass of RuntimeException . Custom exception types are useful when an application is trying to recover from a specific error, rather than just using the same logging or alert mechanism to handle every exception. Programs shouldn't try to recover from specific programming errors like this.

As others have mentioned, there are loads of resources at your disposal (eg this ). Anyway, that aside, I'd be wary of throwing a custom exception. Instead, throw an existing one (eg IllegalArgumentException ) so as to minimize complexity.

A method that is supposed to throw any Exception needs a throw clause:

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

In the method, you need to filter out the cases where you want the exception to be thrown (with if-clauses for example) and then go:

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

In this example, MoneyException is a class that extends Exception:

class MoneyException extends Exception {..}

Throwing an exception is about reporting an error, and it has to be declared as part of the method declaration. For example:

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);
               }
       }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM