gpt4 book ai didi

java - 哪些异常需要方法的 throws 语句?

转载 作者:行者123 更新时间:2023-12-01 23:42:14 25 4
gpt4 key购买 nike

在 Java 中,有一些异常需要 throws 语句:

public void myMethod() throws IOException {
throw new IOException("Error!");
}

而其他人则不然:

public void myOtherMethod() {
throw new IllegalArgumentException("Error!");
}

public void myThirdMethod() {
throw new Error("Error!");
}

如果没有throws,第一种方法将无法编译声明。

判断是否Exception的标准是什么?/Error需要 throws声明?

最佳答案

编译器检查和提示的异常在java中称为检查异常

At compile time, the java compiler checks that a program contains handlers for checked exceptions. Java compiler analyzes by which checked exceptions can result from execution of a method or constructor.For each checked exception which is a possible result, the throws clause for the method or constructor must mention the class or its superclasses of that exception.

从 JLS 了解更多信息:http://docs.oracle.com/javase/specs/jls/se5.0/html/exceptions.html

IOException 是一个检查异常,因此 java 编译器要求您捕获它或抛出它。而 IllegalArgumentException 是一个运行时异常,编译器不会检查或提示。

关于java - 哪些异常需要方法的 throws 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17726033/

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