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. 您可以使用两个不同的例外,例如NumberFormatExceptionandIllegalArgumentException并执行两个不同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. 或者,您可以使用两个不同的构造函数来创建自己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 回答