【发布时间】: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