2016-12-11 3 views
2

私は基本的なプログラミングの試験を準備しています。私は今例外を処理していますが、それをいかに最適に使うかを理解できないようです。私はあなたに最初のコードを与え、次にチェックされた例外を作ることを試みる2番目のコードを与えます。これを入力すると私は感謝しています!例外なしJava、Exception、最良の方法、試験準備

:私の厄介な例外を除いて

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."); 
    } 
+0

のように、呼び出し元のコードでそれを使用してコードを再フォーマットしてください、それが読めない – aleb2000

+1

してその投稿の私たちはそれについて何も理解できません。 –

+0

例外は、通常のロジックを破壊するものに対してのみ使用する必要があります。それはここにあるのでしょうか? –

答えて

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()); 
} 
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ブロックのどこかにスローされたと仮定しますが、あなたの場合はそうではありません)。あなたは、おそらくこのような何かを探している

+0

ありがとうございます!私はどのように "試して" "キャッチ"をスロー "を使用するか分からない。私はいくつかの古い試験で働いています:) – Muriel

+0

@Muriel、あなたはどんな困難に苦しんでいますか? – Andrew

+0

これは非常に悪い考えです。引数に間違いはありません。問題は、口座に十分な資金がないことです。ドメイン例外をスローする必要があります。 – Bohemian

関連する問題