Java,异常,最佳方式,考试准备

时间:2016-12-11 11:22:46

标签: java

我正准备参加基础编程考试。我现在正在处理异常,但似乎无法弄清楚如何最好地使用它。我给你第一个代码,然后是第二个我尝试进行检查异常的代码。对此的任何意见都会让我感激不尽!

,没有例外:

public boolean uttak(int species, int kroner, int skilling) {
     if (species<=this.species && kroner<=this.kroner && skilling <=this.skilling)
     {
         this.species -=species;
         this.kroner -=kroner;
         this.skilling -=skilling;
         return true;
     }
     else return false;

我的凌乱例外:

public void uttak(int species, int kroner, int skilling){
    try{
       if (species<=this.species && kroner<=this.kroner && skilling <=this.skilling)
        {
            this.species -=species;
            this.kroner -=kroner;
            this.skilling -=skilling;
        }
    }
    catch (Exception e){
        System.err.println ("Withdrawals can not be done when there is" +
                             " insufficient money in the machine.");
    }

2 个答案:

答案 0 :(得分:1)

它们都不对我(如果这是关于例外的主题)。

当其中一个方法参数不满足其方法的逻辑时,这是抛出未经检查的异常的好方法:

if (species > this.species || kroner > this.kroner || skilling > this.skilling) {
    throw new IllegalArgumentException("message");
}

如果在方法执行期间遇到逻辑问题,通常应该抛出已检查的异常(您自己的Exception的子类或任何其他特定的已检查异常):

if (species > this.species || kroner > this.kroner || skilling > this.skilling) {
    throw new MyCustomCheckedException("message");
}

没有理由在这个级别上处理异常(假设它被抛出try块中的某个位置,尽管它不在你的情况下。)

答案 1 :(得分:1)

你可能正在寻找这样的东西:

// custom checked exception type
public class WithdrawalException extends Exception {
     public WithdrawalException(String msg) {
         super(msg);
     }
}
public boolean uttak(int species, int kroner, int skilling) throws WithdrawalException { // checked exceptions need to be declared in the throws clause 
     if (species<=this.species && kroner<=this.kroner && skilling <=this.skilling)
     {
         this.species -=species;
         this.kroner -=kroner;
         this.skilling -=skilling;
         return true;
     }
     else
         // throw an exception
         throw new WithdrawalException("Withdrawals can not be done when there is insufficient money in the machine.");
}

并在像这样的调用代码中使用它

try {
    uttak(i1, i2, i3);
} catch (WithdrawalException ex) {
    System.err.println("Something went wrong. Message: "+ex.getMessage());
}