java异常处理无效输入

31moq8wy  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(523)

很难说出这里要问什么。这个问题模棱两可,含糊不清,不完整,过于宽泛,或者是修辞性的,不能以现在的形式得到合理的回答。有关澄清此问题以便重新打开的帮助,请访问帮助中心。
8年前关门了。
我正在尝试java的异常处理。
我无法理解如何从文档中执行此操作,但我要做的是检测无效输入,以便在激活默认案例时引发错误。对我来说,这可能是不正确的逻辑,但我想知道是否有人能用通俗易懂的英语把我推向正确的方向。

  1. char choice = '0';
  2. while (choice != 'q'){
  3. printMenu();
  4. System.in.read(choice);
  5. case '1': DisplayNumAlbums();
  6. case '2': ListAllTitles();
  7. case '3': DisplayAlbumDetail();
  8. case 'q': System.out.println("Invalid input...");
  9. return;
  10. default: System.out.println("Invalid input...");
  11. //Exception handling here
  12. //Incorrect input
  13. }
7rtdyuoh

7rtdyuoh1#

我假设您的错误已经被仔细考虑过了,所以我将使用您自己的代码来制作一个您所要求的用法示例。所以你仍然有责任运行一个程序。
异常处理机制允许您在达到某个错误条件时抛出异常,就像您的情况一样。假设您的方法被调用 choiceOption 您应该这样做:

  1. public void choiceOption() throws InvalidInputException {
  2. char choice = "0";
  3. while (choice != "q"){
  4. printMenu();
  5. System.in.read(choice);
  6. switch(choice){
  7. case "1": DisplayNumAlbums();
  8. case "2": ListAllTitles();
  9. case "3": DisplayAlbumDetail();
  10. case "q": System.out.println("Invalid input...");
  11. return;
  12. default: System.out.println("Invalid input...");
  13. throw new InvalidInputException();
  14. }
  15. }
  16. }

这可以让您在客户端(您拥有的任何客户端:text、fat client、web等)捕获抛出的异常,并让您执行自己的客户端操作,即如果您使用swing,则显示joptionpane;如果您使用jsf作为视图技术,则添加faces消息。
记得吗 InvalidInputException 是必须扩展exception的类。

展开查看全部
btqmn9zl

btqmn9zl2#

如果你的代码在一个方法中,你可以声明这个方法抛出异常,

  1. void method throws Exception(...){}

方法的调用必须在try-catch块中

  1. try{
  2. method(...);
  3. }catch(SomeException e){
  4. //stuff to do
  5. }

或者你可以

  1. while(){
  2. ...
  3. try{
  4. case...
  5. default:
  6. throw new IllegalArgumentException("Invalid input...");
  7. }catch(IllegalArgumentException iae){
  8. //do stuff like print stack trace or exit
  9. System.exit(0);
  10. }
  11. }
展开查看全部

相关问题