JAVA:“错误:未报告的异常异常;必须被捕获或声明被抛出”

时间:2017-05-25 09:05:47

标签: java exception-handling throw

我是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

我需要概念性地了解导致此错误发生的原因。

2 个答案:

答案 0 :(得分:2)

首先你把别人放在错误的地方使用它:

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 {

答案 1 :(得分:1)

Exception之类的异常类派生自Throwable已检查例外,例如Exception未经检查的例外情况,例如IllegalArgumentException

如果您使用后者,则例外是不可见的。

如果检查异常,编译器会强制您获得throws ...catch例外。

这里 IllegalArgumentException 非常适合。