gpt4 book ai didi

java - 什么时候必须在方法声明中使用 "throws"字?

转载 作者:行者123 更新时间:2023-12-01 22:33:29 25 4
gpt4 key购买 nike

我知道这很简单,但作为 java 的新手,我有问题!

这是一个简单的 Java Card 小程序,它在接收到任何命令时返回 SW=0xEE 0xFF:

package secondStep; 
import javacard.framework.*;

public class BadRepeater extends Applet
{
public static void install(byte bArray[], short bOffset, byte bLength) throws ISOException
{
new BadRepeater().register();
}

public void process(APDU arg0) throws ISOException
{
ISOException.throwIt((short)0xeeff);
}
}

我从 process 方法声明行的末尾删除了单词 throws ISOException :

package secondStep; 
import javacard.framework.*;

public class BadRepeater extends Applet
{
public static void install(byte bArray[], short bOffset, byte bLength) throws ISOException
{
new BadRepeater().register();
}

public void process(APDU arg0)
{
ISOException.throwIt((short)0xeeff);
}
}

以上两个程序都可以正常工作。

问题是“有什么区别?”

什么时候我必须在行尾使用单词 throws ... 什么时候不需要?

最佳答案

您必须仅声明已检查的异常。您可以声明未经检查的异常,以表明它们可能会被抛出。

例如 parseInt(String s) 声明它抛出一个 NumberFormatException,即使它没有被检查,因为它很可能会这样做(传递给它而不是一个数字是一个常见的场景)。

来自文档(强调我的):

Runtime exceptions can occur anywhere in a program, and in a typical one they can be very numerous. Having to add runtime exceptions in every method declaration would reduce a program's clarity. Thus, the compiler does not require that you catch or specify runtime exceptions (although you can).

异常层次结构

The Exception Heirarchy

检查或不检查异常取决于它扩展/实现的内容。

所有意外事件的根源是Throwable 接口(interface)。 Throwable有两种类型,ErrorException

Error 用于致命的 JVM 事件,例如 ThreadDeath。您很少需要处理这些事件,因此将它们分开。

Exception 是所有异常(已检查和未检查)的根类型。将检查扩展 Exception 而不是 RuntimeException 的异常。

RuntimeException 扩展 Exception 并允许取消检查。

ISOException 未被选中,因此扩展了 RuntimeException(或者它的父/祖 parent /等等)。在这种情况下,它扩展了 CardRuntimeException,后者扩展了 RuntimeException ( based on the Javadoc I found )

关于java - 什么时候必须在方法声明中使用 "throws"字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28431137/

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