0
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            System.out.println(" Enter the Amount of articles to be ordered.");
            amount = reader.readLine();

            if(amount.trim().isEmpty()){
                System.out.println("Amount Entered is Empty");
            }

            for(int count=0;count<amount.length();count++){
                if(!Character.isDigit(amount.charAt(count))){
                    throw new NumberFormatException();
                }
            }            
            order.validateAmount(amount);
        }catch(NumberFormatException numbere){
            System.out.println("Either Number format is uncorrect or String is Empty, Try Again.");
    }

上記のコードは、空の文字列の例外と無効な数値データの例外の両方に対して単一の println() ステートメントを提供しますが、これは望ましくありません。両方の例外に対して個別の println() ステートメントが必要です。取得する方法?

4

2 に答える 2

1
  1. 2つの異なる例外を使用することNumberFormatExceptionもできIllegalArgumentExceptionます。catch

        ...
        if (amount.isEmpty())
            throw new IllegalArgumentException();
        ...
    
    } catch (NumberFormatException numbere) {
        System.out.println("Either Number format is uncorrect, Try Again.");
    } catch (IllegalArgumentException empty) {
        System.out.println("String is empty, Try Again.");
    }
    
  2. 同じ例外を使用しますが、メッセージは異なります

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                System.in));
        System.out.println(" Enter the Amount of articles to be ordered.");
        String amount = reader.readLine();
    
        if (amount.trim().isEmpty()) {
            System.out.println("Amount Entered is Empty");
        }
    
        if (amount.isEmpty())
            throw new IllegalArgumentException("String is empty.");
    
    
        for (int count = 0; count < amount.length(); count++)
            if (!Character.isDigit(amount.charAt(count)))
                throw new IllegalArgumentException("Number format incorrect.");
    
        order.validateAmount(amount);
    } catch (IllegalArgumentException e) {
        System.out.println(e.getMessage() + " Try again.");
    }
    
  3. または、2 つの異なるコンストラクターと、例外が不正な数値または空の文字列によるものかどうかを示すフラグを使用して、独自のコンストラクターを作成することもできます。Exception

于 2011-04-21T06:11:31.177 に答える
1

空の文字列は「予期される」例外であるため、例外を使用せずにチェックします。

if ( amount.trim().equals( string.empty) )
{
   System.out.println("string empty" );
}
else
{
   //do your other processing here
}

空の別のチェックは次のようになりますamount.trim().length == 0

本当に例外を使用したい場合:

if( amount.trim().equals( string.empty) )
{
   throw new IllegalArgumentException( "Amount is not given" );
}

別の catch() を追加します

}
catch( NumberFormatException numbere)
{
}
catch( IllegalArgumentException x )
{
  // Amount not given
}
于 2011-04-21T06:12:42.020 に答える