在Java中尝试/捕获

时间:2010-01-14 23:01:23

标签: java exception exception-handling try-catch java.util.scanner

有人可以给我一个提示,为什么这个尝试和捕获不起作用? 它会抛出扫描程序异常,而不是打印我期望的消息。

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;
    }
}

7 个答案:

答案 0 :(得分:21)

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

例如,当你说:

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

仅指定如何捕获NumberFormatException 为了捕获所有异常,你需要做到:

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

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

但是,由于自己捕获异常是不受欢迎的,所以你也可以这样做:

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

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

答案 1 :(得分:4)

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

答案 2 :(得分:2)

您需要捕获 ScannerException 或类似的内容。

在此代码中,您只能捕获 NumberFormatException

尝试这样的事情:

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

答案 3 :(得分:1)

你遇到了错误的例外。

答案 4 :(得分:0)

您的代码不会抛出NumberFormatException。你应该抓住InputMismatchException

nextDouble中查看Scanner,似乎Scanner代码为您处理NumberFormatException,然后抛出不同类型的异常:

来自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());
    }
} 

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

另请注意,JDK中没有ScannerException

答案 5 :(得分:0)

抓住InputMismatchException代替NumberFormatException,一切正常。

答案 6 :(得分:0)

为什么不这样做:

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);

仅供参考,双精度的实际正则表达式为[数字] [。] [数字],[。] [数字]是可选的。

相关问题