Catch语句错误代码

时间:2015-04-24 23:05:40

标签: java

我尝试设置我的程序,提示用户将值yn输入到名为resetValue的字符串中,我try传递值为char r。我知道代码有一些错误,但我很好奇我的catch语句的错误代码应该是什么。如果用户输入了yn以外的无效值。我只是在Oracle网站上查看错误列表,但有很多我不知道哪一个最适合这个问题。

// Prompts the user to reset the program from the beginning if they wish
while(true){

System.out.print("\nWould you like to enter some new numbers? Type (y) or (n): ");
resetValue = input.readLine();

   try {
      char r = resetValue.charAt(0);
      if( r == y || r == Y ){
         break;
      }
      else if( r == n || r == N){
          reset = true;
          break;
      }
   }
   catch (ERROR STATUS HERE) {
        System.out.print("Please type either (y) or (n) on the keyboard.");
   }
}

2 个答案:

答案 0 :(得分:1)

根据readLine的性质,您的代码不应抛出任何异常为运行时异常保存,例如NullPointerException。抓住那些不可取的,因为那些表示错过了关于代码状态的事情的假设(例如你的输入流已经以某种方式关闭)。

省略try/catch阻止。

接下来,如果用户输入了无效选项,会给他们一个纠正错误的机会。您需要做的就是设置一个else条件(除了修复那些字符文字)并继续循环,直到它可以在有效输入上中断。

段:

} else {
    System.out.println("Invalid input - please enter only Y or N");
}

答案 1 :(得分:-2)

继承Exception类并创建自己的Exception!

public class YourException extends Exception 
{
    private static final long serialVersionUID = 1L;  //You need this. Use a random long


    @Override
    public String toString()
    {
        return "Some message";
    }
}