gpt4 book ai didi

java - 如何在java中编写未经检查的异常?

转载 作者:行者123 更新时间:2023-11-30 07:09:27 25 4
gpt4 key购买 nike

是否可以在 Java 中编写未经检查的异常?也许告诉编译器在编译时不要检查抛出是个好主意吗?

JVM 如何区分已检查异常和未检查异常?是 JVM 还是 Java 类级别?

最佳答案

未经检查的异常主要是编译器级别的,因为它们在内部以相同的方式被抛出。唯一的区别是它们在代码和方法签名中的明确要求。

您通过继承 RuntimeException 而不是 Exception 创建未经检查的异常。

JLS 11.2 states :

The Java programming language requires that a program contains handlers for checked exceptions which can result from execution of a method or constructor (§8.4.6, §8.8.5). This compile-time checking for the presence of exception handlers is designed to reduce the number of exceptions which are not properly handled. For each checked exception which is a possible result, the throws clause for the method or constructor must mention the class of that exception or one of the superclasses of the class of that exception (§11.2.3).

....

The unchecked exception classes (§11.1.1) are exempted from compile-time checking.

关于java - 如何在java中编写未经检查的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23117762/

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