Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java中引发一般异常_Java_Error Handling - Fatal编程技术网

在Java中引发一般异常

在Java中引发一般异常,java,error-handling,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"); } } 但是我得到了错误

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

我正在尝试这样做:

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");
        }
    }
但是我得到了错误

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


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");
    }
}

谢谢,我现在明白了,但是为什么需要在函数头中抛出它呢?我认为更好的问题是为什么要检查异常?@PawelK,因为
exception
及其所有子项都必须在检查
exception
s时声明。
RuntimeException
的子项未选中,因此不需要声明。这就是规则。我没有料到会有这样的规则,我觉得应该可以在任何地方抛出异常,它是一个检查过的异常,而不是运行时异常,这意味着您必须在方法签名中声明抛出异常。这会警告该方法的所有调用者期望出现异常,以便他们可以相应地采取行动。@PawelK你是怎么想的?当然,将可能遇到的错误情况告知调用代码是有意义的,不是吗?