Java 中抛出一般异常

Paw*_*l K 4 java error-handling

这是关于抛出异常的在线教程

我正在尝试做这样的事情:

int power(int n, int p){
        try
        {
            return (int)Math.pow(n,p);
        }
        catch(Exception e)
        {
            throw new Exception("n and p should be non-negative");
        }
    }
Run Code Online (Sandbox Code Playgroud)

但我得到了错误

错误:未报告的异常Exception;必须被抓住或宣布被扔出

Era*_*ran 5

Exception是一个检查异常,这意味着如果一个方法想要抛出它,它必须在子句中声明它throws

int power(int n, int p) throws Exception {
    try
    {
        return (int)Math.pow(n,p);
    }
    catch(Exception e)
    {
        throw new Exception("n and p should be non-negative");
    }
}
Run Code Online (Sandbox Code Playgroud)