【问题标题】:Is it possible to have two catches with the same Exception type from two different methods?是否可以从两个不同的方法中获得两个具有相同异常类型的捕获?
【发布时间】:2019-08-13 10:14:29
【问题描述】:

我是新来的编程新手,如果这太长了,很抱歉。我确信有一种更简单的方法可以做到这一点,但我真的很想看看这是否能得到解决。
我正在开发一个程序,该程序接受用户输入(双精度)并从摄氏转换为华氏(cToF),反之亦然(fToC),约束为 0 到 1000。我对 cToF 和 fToC 都有单独的方法。
我想在用户不输入双精度时抛出异常。我主要有 catch (InputMismatchException cToF) 和 catch (InputMismatchException2 fToC) 来做不同的事情。
另外,我怀疑 fToC 的数学是不正确的,我还没弄明白。

我尝试将 InputMismatchException2 的名称更改为 InputMismatchException,但我得到“异常已被捕获”。 我已经导入了 java.util.*。
我尝试在主要方法和两种转换方法的开头添加“抛出异常”。
我不确定 try-catch 是否应该在主方法、单个方法或两者中。

public static void main(String args[]) throws InputMismatchException, InputMismatchException2 {

    Scanner choice = new Scanner(System.in);
    String unit = "n";
    boolean typo = false;
    double tempC = 0;
    double tempF = 0;

    try {
        start();//method to determine conversion type (F-C or C-F)

        if (typo == false) {

            do {//forever loop

                question(unit);

            }//end do loop
            while (typo == false);

        }//end if

        System.out.println("Thank you, goodbye!");

    }//end try

    catch (InputMismatchException cToFE) {//if a non-double is entered

        System.out.println("The value " + tempC + " is not within previously defined constraints.");
        System.out.println("Please enter a new value.");
        cToF(unit);

    }//end cToF catch

    catch (InputMismatchException2 fToCE) {//if a non-double is entered

        System.out.println("The value " + tempF + " is not within previously defined constraints.");
        System.out.println("Please enter a new value.");
        fToC(unit);

    }//end fToC catch

}//end main method

public static void cToF(String unit) throws InputMismatchException {

    System.out.println();
    System.out.println("Please enter a value from 0 to 1000.");//CONSTRAINTS: 0 <= temp <= 1000

    Scanner temp = new Scanner(System.in);
    double tempC = temp.nextDouble();

    if (0 <=  tempC && tempC <= 1000) {//if tempC is within constraints

        double tempF = (tempC * 1.8) + 32;//arithmetic with tempC == tempF

        System.out.println(tempC + " degrees Celsius is " + tempF + " degrees Fahrenheit");//print conversion

    }//end if
    else if (tempC < 0 || tempC > 1000) {//if tempC is NOT within constraints

        System.out.println("The value " + tempC + " is not within previously defined constraints.");
        System.out.println("Please enter a new value.");
        cToF(unit);

    }//end else if
    else {//if non-double entered

        //InputMismatchException cToFE = new InputMismatchException();
        throw new InputMismatchException();

    }//end else

}//end cToF method

public static void fToC(String unit) throws InputMismatchException2 {

    System.out.println();
    System.out.println("Please enter a value from 0 to 1000.");//CONSTRAINTS: 0 <= temp <= 1000

    Scanner temp = new Scanner(System.in);
    double tempF = temp.nextDouble();

    if (0 <=  tempF && tempF <= 1000) {//if tempF is within constraints

        double tempC = (32 - tempF) / 1.8;//arithmetic with tempF == tempC
        System.out.println(tempF + " degrees Fahrenheit is " + tempC + " degrees Celsius");//print conversion

    }//end if
    else if (tempF < 0 || tempF > 1000) {//if tempF is NOT within constraints

        System.out.println("The value " + tempF + " is not within previously defined constraints.");
        System.out.println("Please enter a new value.");
        fToC(unit);

    }//end else if
    else {//if non-double entered

        //InputMismatchException2 fToCE = new InputMismatchException2();
        throw new InputMismatchException2();

    }//end else

}//end fToC method

我想要什么:
如果用户在任一方法 (fToC/cToF) 中键入字母,则打印 [tempF/tempC 分别] 不在先前定义的约束范围内。请输入一个新值。
然后递归调用任一方法重新启动临时输入过程。

我得到了什么(使用当前代码):

$ javac Temperature.java
Temperature.java:5: error: cannot find symbol
    public static void main(String args[]) throws InputMismatchException, InputMismatchException2 {
                                                                          ^
  symbol:   class InputMismatchException2
  location: class Temperature
Temperature.java:125: error: cannot find symbol
    public static void fToC(String unit) throws InputMismatchException2 {
                                                ^
  symbol:   class InputMismatchException2
  location: class Temperature
Temperature.java:42: error: cannot find symbol
        catch (InputMismatchException2 fToCE) {//if a non-double is entered
               ^
  symbol:   class InputMismatchException2
  location: class Temperature
Temperature.java:151: error: cannot find symbol
            throw new InputMismatchException2();
                      ^
  symbol:   class InputMismatchException2
  location: class Temperature
4 errors

【问题讨论】:

  • 一开始我在start()方法中调用了cToF/fToC。我的理解是,当它在 cToF 方法中并引发异常时,我可以让 catch 打印错误消息,然后再次调用该方法,对吗?这就是为什么我希望 InputMismatchException 与 InputMismatchException2 会有所帮助。

标签: java try-catch inputmismatchexception


【解决方案1】:

简而言之,no,你不能这样做。否则,将无法确定在抛出异常时执行正确的 catch 语句。

您的错误是“错误:找不到符号”。根据错误跟踪,这意味着找不到符号InputMismatchException2。本质上,如果你想抛出一个InputMismatchException2,你需要定义一个单独的类InputMismatchException2(扩展InputMismatchException)。然后您可以运行您的代码的原因是您实际上会抛出和捕获两种不同类型的InputMismatchExceptionInputMismatchExceptionInputMismatchException2

但是!初始化InputMismatchException with a message 并使用其getMessage 方法在catch 语句中提取相关信息可能会好得多。

仔细看代码,generallynotrecommended 使用异常作为控制流的一部分。

【讨论】:

  • 我在main方法中初始化它吗?内试还是外试?因为这不是一种新方法,对吧?
  • 初始化什么?例外? throw new InputMismatchException("something didn't match!"); 会成功的。
  • 当您执行catch(InputMismatchException ime) { ... } 时,您希望将异常中的值用作ime.getMessage()
  • @castiyeaux 我做了一个快速演示here。将打印的内容是:this will printSomething went wrong: something didn't match!
  • 我明白了!最后两个 cmet 帮助很大。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
  • 2016-11-14
  • 1970-01-01
  • 1970-01-01
  • 2021-10-14
  • 2012-06-28
相关资源
最近更新 更多