2017-10-11 90 views
-4

我有一个使用开关的驱动菜单类,除了那个类,该类抛出一个异常,当输入一个错误的输入时,我怎么能得到异常后,并要求用户输入数据再次。java类,异常,用户输入

java类金刚石:

public class Diamond 
{ 

private int x; 

    public Diamond(int x) throws IllegalArgumentException 
    { 
     if ((x % 2) == 0) 
     { 
      System.out.println("\nx must be odd."); 
      throw new IllegalArgumentException("x must be odd."); 

     } 
     this.x = x; 

    } 
+0

为什么要在无效输入上抛出运行时异常? –

+0

不要抛出异常....只需将一条消息打印到控制台:'System.out.println(“Supplied value must be odd!”);'。 – DevilsHnd

回答

0

请参阅this question regarding exceptions in general以及this Java Tutorial

我假设你有一些代码接受用户输入,然后创建一个Diamond类的实例。

您会将创建Diamond实例的代码包装在try-catch块中。

所以,这样的事情:

Diamond d = null; 
try{ 
    d = new Diamond(userInput); 
}catch(IllegalArgumentException e){ 
    //Handle the exception 
} 

然而,由于这种异常是由于抛出一个输入的问题,而不是一个规划问题,我倾向于对,你应该在这里使用一个检查异常的想法倾斜。

按照该Java Tutorial一般规则:

如果客户可以合理预期从异常中恢复,使它成为一个检查异常。如果客户端无法做任何事情来恢复异常,请将其设为未检查的异常。