gpt4 book ai didi

java - JAVA中的异常处理及throws语句的使用

转载 作者:行者123 更新时间:2023-11-29 10:11:49 24 4
gpt4 key购买 nike

为什么会这样?此代码编译正常但在运行时抛出异常

public class Except
{
public static void main(String args[])
{
System.out.println("Hey, I am under main");
method();
}
static void method()
{
throw new NullPointerException();
}
}

但是这段代码没有编译

public class Expect
{
public static void main(String args[])
{
System.out.println("Hey, I am under main");
method();
}
static void method()
{
throw new IllegalAccessException();
}
}

为什么会这样?改变异常的类型,第二个代码没有编译。有人能解释一下吗,我在第一个代码中使用了 throw 语句,并且编译正常,那么有什么用编写带有方法声明的 throws 语句。我使用的是 jdk 1.8.0_45

最佳答案

NullPointerExceptionRuntimeException 的子类,这使它成为一个未经检查的异常,不必在 throws 子句中处理或声明。

IllegalAccessException是一个已检查的异常,因此它必须被捕获或在任何可能抛出它的方法的 throws 子句中声明。

如果您添加一个 throws 子句,第二个片段将编译:

static void method() throws IllegalAccessException
{
throw new IllegalAccessException();
}

关于java - JAVA中的异常处理及throws语句的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31132185/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com