【问题标题】:can we catch two exceptions at once in java?我们可以在java中一次捕获两个异常吗?
【发布时间】:2014-10-17 17:36:06
【问题描述】:

我正在用java编写代码,我遇到了这个错误:

try {
         //can't use the memberlist??


         System.out.println("Login successful! Welcome back!");

         member.memberProfile.setFirstName("Jane");
         member.memberProfile.setLastName("Doe");
         member.memberProfile.setAddress("123, Foster avenue, Chicago, US");
         member.memberProfile.setPhone("7735249286");
         member.memberProfile.setInterests("music");


        System.out.println("Do you wish to change your user information? Please type 'yes' or 'no': ");
        String choice= input.nextLine();

        if(choice.equals("yes")){
             member.memberProfile.Update_Details();
        }
        System.out.println("Your user information is: ");
        System.out.print(member.memberProfile.toString());

    } catch(UserNotFoundException | WrongAnswerException e ){
         System.out.println(e.getMessage());
         tries ++;
    }

catch(UserNotFoundException | WrongAnswerException e ) 这行有问题 它说我需要删除UserNotFoundExceptionWrongAnswerException 当我这样做时,它说我必须删除整个 catch 块。我能做些什么?

【问题讨论】:

  • 这是什么itit 显示的确切错误消息是什么?请注意,try-multicatch 自版本 7 以来仅在 Java 中使用,因此如果您的项目设置为较低的 Java 版本,则无法使用它。
  • 在 SE7 中添加了 catch(a|b ex) 语法。什么是说你必须删除整个块?
  • 这个 try 块是否真的抛出了这些异常中的任何一个?
  • @JohnKugelman 不,我没有扔它们,你能告诉我怎么做吗?

标签: java exception try-catch


【解决方案1】:

如果它们都是检查异常(即它们不是RuntimeException 的子类),那么如果try 块中的代码都没有抛出这些异常,编译器会报错。它不会让您捕获静态分析显示从未抛出的异常。

这与使用 multi-catch | 语法无关。

【讨论】:

  • 我没有创建 RuntimeException 类。但是,我做了这两个例外类。你能告诉我如何把它们扔到哪里吗?
  • @jungkookie 这完全是一个不同的问题。 Read the oracle tutorial here:
  • @jungkookie Erm...“怎么样”是throw new WhateverException()。 “哪里”是您需要的任何地方。
【解决方案2】:

你在做一个逻辑或

分解catch块

}catch(UserNotFoundException userNotFound ){
        System.out.println(UserNotFound.getMessage());
        tries ++;
    }
}catch(WrongAnswerException wrongAnswer ){
        System.out.println(wrongAnswer.getMessage());
        tries ++;
    }

【讨论】:

  • | 语法实际上在 java 中对异常有效。 (至少,通常情况下;显然 OP 有问题)。
猜你喜欢
  • 2019-09-30
  • 1970-01-01
  • 2011-03-30
  • 2021-08-25
  • 2015-04-02
  • 2017-06-24
  • 1970-01-01
  • 2014-07-29
  • 2017-03-10
相关资源
最近更新 更多