在 Java 中尝试/捕获

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2068186/
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-08-13 03:12:53  来源:igfitidea点击:

Try/catch in Java

javaexceptionexception-handlingtry-catchjava.util.scanner

提问by Tony

Could someone please give me a hint why this try and catch is not working? It throws a scanner exception instead of printing the message I expect.

有人可以给我一个提示,为什么这个 try and catch 不起作用?它会引发扫描仪异常,而不是打印我期望的消息。

import java.util.*;
import java.io.*;
import java.math.*;
import javax.swing.*;

public class Main {
    public static void main(String[] args) {
        Boolean test = true;
        while (test == true) {
            try {
                double x, y;
                String operator;
                Scanner scan = new Scanner(System.in);
                Scanner scan_2 = new Scanner(System.in);
                Scanner ScanOperator = new Scanner(System.in);
                System.out.println(" Enter a double value: ");
                x = scan.nextDouble();
                System.out.println(" Enter another double value: ");
                y = scan_2.nextDouble();
                System.out.println(" Enter a operator for the operation you want to execute, or X if you want to quit: ");
                operator = ScanOperator.nextLine();
                if (operator.equals("x") || operator.equals("X")) {
                    test = false;
                    System.out.println("No calculation was made!!!");
                }
                System.out.println(Calculation(operator, x, y));
            } catch (NumberFormatException nfe) {
               JOptionPane.showMessageDialog(null,"Input must be a number.");
            }
        }
    }

    public static double Calculation(String operator, double x, double y) {
        double result = 0;
        double myAdd = 0;
        double mySub = 0;
        double myMult = 0;
        double myDiv = 0;
        double myPower = 0;
        double myMod = 0;

        if (operator.equals("+")) {
            myAdd = x + y;
            result = myAdd;
        } else if (operator.equals("-")) {
            mySub = x - y;
            result = mySub;
        } else if (operator.equals("*")) {
            myMult = x * y;
            result = myMult;
        } else if (operator.equals("/")) {
            myDiv = x / y;
            result = myDiv;
        } else if (operator.equals("^")) {
            myPower = Math.pow(x, y);
            result = myPower;
        } else if (operator.equals("%")) {
            myMod = x % y;
            result = myMod;
        } else {
        }

        return result;
    }
}

回答by Anon.

You're catching the wrong exception.

你捕捉到了错误的异常。

回答by Jeff

You're attempting to catch a NumberFormatException. You need to add a catch statement for a ScannerException, as it is different from a NumberFormatException.

您正在尝试捕获 NumberFormatException。您需要为 ScannerException 添加 catch 语句,因为它与 NumberFormatException 不同。

回答by Pedro Ghilardi

You need to catch a ScannerExceptionor some like this.

您需要捕获ScannerException或类似的异常

At this code you are only catching the NumberFormatException.

在此代码中,您只捕获NumberFormatException

Try some like this:

尝试一些这样的:

    try {
       ...
    } catch (NumberFormatException, ScannerException exception) {
       JOptionPane.showMessageDialog(null,"Input must be a number.");
    }

回答by zmbush

Simple, the program throws ScannerException, but your try catch can only catch NumberFormatException, you need to add another catch clause in order to catch ScannerException, or catch only the generic Exception.

很简单,程序抛出ScannerException,但是你的try catch只能捕获NumberFormatException,你需要添加另一个catch子句才能捕获ScannerException,或者只捕获通用的Exception。

for example, when you say:

例如,当你说:

 } catch (NumberFormatException nfe) {     
     JOptionPane.showMessageDialog(null,"Input must be a number.");
 }

that is only specifying how to catch NumberFormatException.
In order to catch all exceptions, you would need to make it:

那只是指定如何捕获 NumberFormatException。
为了捕获所有异常,您需要执行以下操作:

 } catch (NumberFormatException nfe) {     
     JOptionPane.showMessageDialog(null,"Input must be a number.");
 }catch (Exception e){
     JOptionPane.showMessageDialog(null,"Generic exception caught");
 }

In this case, the second catch would get everything that was not caught in the first catch because all exceptions extend the Exception class, you can catch all derived classes with that statement.

在这种情况下,第二个 catch 将获取第一个 catch 中未捕获的所有内容,因为所有异常都扩展了 Exception 类,您可以使用该语句捕获所有派生类。

However, since catching Exception by itself is frowned upon, you could also do:

然而,由于捕获 Exception 本身是不受欢迎的,你也可以这样做:

 } catch (NumberFormatException, ScannerException e) {     
     JOptionPane.showMessageDialog(null,"Input must be a number.");
 }

To catch both exceptions in the same block.

在同一块中捕获两个异常。

回答by akf

Your code will not throw a NumberFormatException. You should catch an InputMismatchExceptioninstead.

您的代码不会抛出NumberFormatException. 你应该抓住一个InputMismatchException

Looking at nextDouble, in Scanner, it seems that the Scannercode handles the NumberFormatExceptionfor you and then throws a different type of exception:

看着nextDouble, in ScannerScanner代码似乎NumberFormatException为您处理了,然后抛出了不同类型的异常:

from java.util.Scanner:

来自java.util.Scanner

public double nextDouble() {
    // Check cached result
    if ((typeCache != null) && (typeCache instanceof Double)) {
        double val = ((Double)typeCache).doubleValue();
        useTypeCache();
        return val;
    }
    setRadix(10);
    clearCaches();
    // Search for next float
    try {
        return Double.parseDouble(processFloatToken(next(floatPattern())));
    } catch (NumberFormatException nfe) {
        position = matcher.start(); // don't skip bad token
        throw new InputMismatchException(nfe.getMessage());
    }
} 

When you hit a problem like this, I recommend that you look through the Java source as a first stop. It is a great resource.

当您遇到这样的问题时,我建议您首先查看 Java 源代码。这是一个很好的资源。

Also note that there is no ScannerExceptionin the JDK.

另请注意,ScannerExceptionJDK 中没有。

回答by Thunderhashy

Just catch InputMismatchExceptioninstead of NumberFormatExceptionand everything works fine.

只需捕获InputMismatchException而不是NumberFormatException一切正常。

回答by Droo

Why not just do:

为什么不这样做:

String input = scan.nextLine();
if(!input.matches("\d+")) { // regex for 1 or more digits
    System.err.println("Input must be at least 1 digit!");
    continue; // goes back to the top of the loop
}
double dbl = Double.valueOf(input);

FYI, the actual regex for double precision would be [digit][.][digit] with the [.][digit] being optional.

仅供参考,双精度的实际正则表达式为 [digit][.][digit] ,其中 [.][digit] 是可选的。