【问题标题】:JAVA: "error: unreported exception Exception; must be caught or declared to be thrown" [duplicate]JAVA:“错误:未报告的异常异常;必须被捕获或声明为抛出”[重复]
【发布时间】:2017-05-25 09:05:46
【问题描述】:

我是 JAVA 编程的新手,遇到了需要打印两个非负数的指数结果的代码。如果其中任何一个为负数,我需要抛出一个异常,我的代码如下:`

import java.util.*;
import java.util.Scanner;

class MyCalculator {

    int power(int n, int p) {
        int result = 1;
        if (n < 0 || p < 0) {
            throw new Exception("n and p should be non-negative");
            else
        {
        while(p!=0)
            {
            result=result*n;
            p-=1;
        }
        return result;
    }
        }
    }

    class Solution {

        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);

            while (in.hasNextInt()) {
                int n = in.nextInt();
                int p = in.nextInt();
                MyCalculator my_calculator = new MyCalculator();
                try {
                    System.out.println(my_calculator.power(n, p));
                } catch (Exception e) {
                    System.out.println(e);
                }
            }
        }
    }

我收到上面写的错误 IE:

error: unreported exception Exception; must be caught or declared to be thrown

我需要从概念上了解导致此错误发生的实际原因。

【问题讨论】:

  • 然后谷歌“java异常”。这被记录了无数次。
  • 你的程序甚至不会编译成功。

标签: java exception-handling throw


【解决方案1】:

首先你把 else 放在了错误的地方,改用这个:

int result = 1;
if (n < 0 || p < 0) {
    throw new Exception("n and p should be non-negative");
} else {
^---------------------------------You have to close the if, then use else
    while (p != 0) {
        result = result * n;
        p -= 1;
    }
    return result;
}

第二你的方法应该是throws Exception

int power(int n, int p) throws Exception {

【讨论】:

  • 好点,但我会省略 catch 示例。空 catch 块从来都不是一个好主意,然后 throw 再空 catch 是超级疯狂的。
  • 谢谢@GhostCat,所以ex.printStackTrace(); 可以做到这一点,或者我应该怎么做才能不让它为空?
  • 在这种情况下捕捉是没有意义的。您可以展示 pow() 的用户如何捕获。
  • 是的,这是正确的 @GhostCat OP 已经使用 try { System.out.println(my_calculator.power(n, p)); } catch (Exception e) { System.out.println(e); } 所以他不需要在 pow() 方法中再次使用它
【解决方案2】:

Exception 等异常类派生自 Throwable。 有像Exception 这样的已检查 异常和像IllegalArgumentException 这样的未检查 异常。

如果您使用后者,则异常将不可见。

对于已检查的异常,编译器会强制您拥有 throws ...catch 异常。

这里的 IllegalArgumentException 非常适合。

【讨论】:

  • 如何知道异常是否在官方文档中被选中?
  • 未经检查的异常扩展了 RuntimeException,即扩展了扩展 Throwable 的 Exception。 已检查异常 扩展异常,而不是 RuntimeException。并且罕见的 Errors 扩展 Throwable,而不是 Exception。见于 javadoc 的顶部。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多