简体   繁体   English

如何在Java中引发异常?

[英]How do I throw an exception in java?

Hmm.. Here is the instruction given to me: 嗯..这是给我的指示:

Supports addition & subtraction with other Money object 支持与其他Money对象进行加减运算
Throws exception if currencies are incompatible. 如果货币不兼容,则引发异常。

Hmm.. I already got a money class with add() in it. 嗯..我已经有了一个带有add()的货币类。 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? 还是应该在发生其他所有事情的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);
    }
}
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. 但是,我会考虑创建一个特定于应用程序或Money异常,根据您的需要将ExceptionRuntimeException子类RuntimeException

Perhaps a MoneyConversionException extending MoneyException if things have to be granular. 如果事情必须MoneyException话,可能是MoneyConversionException扩展了MoneyException

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. 由于IllegalArgumentException派生自RuntimeException ,因此您无需声明add()方法可以抛出它。

Do not create a custom subclass of RuntimeException . 不要创建一个自定义子类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 ). 正如其他人提到的那样,您有很多资源可供使用(例如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. 而是抛出一个现有的(例如IllegalArgumentException )以最小化复杂性。

A method that is supposed to throw any Exception needs a throw clause: 应该抛出任何Exception需要throw子句:

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: 在该方法中,您需要过滤掉要引发异常的情况(例如,如果有if子句),然后执行以下操作:

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

In this example, MoneyException is a class that extends Exception: 在此示例中,MoneyException是扩展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);
               }
       }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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