java switch 块 try/catch 异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35279755/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 23:56:32  来源:igfitidea点击:

switch block try/catch exception

javaswitch-statement

提问by Rassisland

I have a switchstatement with 5 integer options and a default message. I am trying to get it to work so that if anything other than the choice numbers is chosen, an "Invalid Input" message will show up. It currently works for numbers, but if anything else is entered, I get the following exception:

我有一个switch带有 5 个整数选项和一个默认消息的语句。我试图让它工作,以便如果选择了选择数字以外的任何其他内容,则会显示“无效输入”消息。它目前适用于数字,但如果输入任何其他内容,我会收到以下异常:

Exception in thread "main" java.util.InputMismatchException

线程“main”中的异常 java.util.InputMismatchException

I tried to add a try/catch statement, but it doesn't seem to be working; I keep getting the same error message.

我试图添加一个 try/catch 语句,但它似乎不起作用;我不断收到相同的错误消息。

public static void main(String[] args) throws IOException {
    int menuItem = -1;
    while (menuItem != 0) {
        menuItem = menu();
        try {
            switch (menuItem) {
                case 1:
                    showTaskList();
                    break;
                case 2:
                    addTask();
                    break;
                case 3:
                    sortList();
                    break;
                case 4:
                    deleteTasks();
                    break;
                case 0:
                    break;
                default:
                    System.out.println("Invalid Input");
                    break;
            }
        }
        catch (java.util.InputMismatchException err) {
            System.out.println("\nINVALID INPUT!");
        }
    }
}

采纳答案by John Bollinger

If your program terminates with a java.util.InputMismatchExceptionthen it follows that that exception was not thrown from within the tryblock you presented. Inasmuch as that exception is associated with entering input in an unexpected form, and inasmuch as an attempt to convert the input to a number evidently has already been performedin method menu(), before entering the tryblock, it seems reasonable to conclude that the exception is thrown from method menu(). The stack trace accompanying the exception would have told you this directly, and more precisely than I can from what you presented.

如果您的程序以 a 终止,java.util.InputMismatchException则表明该异常不是从try您提供的块内抛出的。由于该异常与以意外形式输入输入相关联,并且由于在 method 中显然已经执行了将输入转换为数字的尝试menu(),因此在进入try块之前,推断异常是从方法menu()。伴随异常的堆栈跟踪会直接告诉您这一点,并且比我从您提供的内容中可以更准确地告诉您。

Based on the nature of the task and the type of exception you received, I speculate that you are using a Scannerto read user input, and specifically that you are invoking Scanner.nextInt(). This method will throw an exception of the type you specified if invoked when the next token cannot be interpreted as a Java int.

根据任务的性质和您收到的异常类型,我推测您正在使用 aScanner来读取用户输入,特别是您正在调用Scanner.nextInt(). 如果在下一个标记无法解释为 Java 时调用此方法,则会抛出您指定的类型的异常int

Only you can decide how bestto deal with that, but one possibility is to move invocation of the menu()method inside your tryblock:

只有您可以决定如何最好地处理它,但一种可能性是menu()try块内移动方法的调用:

    // ...
    while (menuItem != 0) {
        try {
            menuItem = menu();
            switch (menuItem) {
            // ...