java - IllegalAccessError 和 IllegalAccessException 的区别

标签 java exception-handling error-handling

考虑这对 Throwable:

IllegalAccessExceptionextends Exception

Thrown when an application tries to reflectively create an instance (other than an array), set or get a field, or invoke a method, but the currently executing method does not have access to the definition of the specified class, field, method or constructor.

IllegalAccessErrorext IncompatibleClassChangeError ext LinkageError ext Error

Thrown if an application attempts to access or modify a field, or to call a method that it does not have access to.

Normally, this error is caught by the compiler; this error can only occur at run time if the definition of a class has incompatibly changed.

问题

  • 有人可以给出抛出每个的代码示例吗?
  • 名字的相似是否暗示了两者之间的关系,还是纯属巧合?
  • 还有其他 XXXErrorXXXException 组合吗?这些对彼此有什么关系?
  • 如果您显式尝试捕获异常/错误对中的一个,您是否也应该捕获其他?

最佳答案

Can someone give a code example where each is thrown?

当您尝试使用反射调用方法或读取或写入 Java 可见性规则禁止的字段时,将抛出 IllegalAccessException

IllegalAccessError 不能被一致编译的 Java 代码抛出。例如,当您加载一个试图调用方法的类或读取或写入另一个类中 Java 可见性规则禁止的字段时,就会发生这种情况。这是编译器通常会阻止的事情,因此这意味着这些类存在严重错误。无论如何,这被认为是一个“错误”;即不可恢复,类加载器将拒绝加载有问题的类。

Does the similarity in name imply relationship between the two, or is it just pure coincidence?

两者之间有着明确的关系。区别在于两者发生的环境不同。

Are there other XXXError and XXXException combo? How are the pairs related to each other?

通过。检查 javadoc。

If you explicitly try to catch one in an Exception/Error pair, should you also catch the other?

可能不会。 XXXError 和 XXXException 通常发生在不同的情况下。 (这当然适用于反射与类加载器。)

此外,作为一般规则,您不应 try catch Error 的子类型并从中恢复。将 ErrorException 分开的全部意义在于区分不可恢复和(可能)可恢复的异常。

在这种情况下,普通应用程序无法从 IllegalAccessError 中恢复。如果您尝试重复导致问题的类加载器操作,它只会再次发生。

关于java - IllegalAccessError 和 IllegalAccessException 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3074635/

相关文章:

python - 如何处理 numpy 中的 np.RankWarning?

ios - EXC_BAD_ACCESS 自动处理

swift - “ fatal error :在展开可选值时意外发现nil”是什么意思?

google-apps-script - 从Google Apps脚本后端在客户端记录完整异常(exception)

javascript - 拉维 Vue.js : Error in render: "TypeError: Cannot read property ' user' of null"

java - 如何在rest api中使用xml/json请求发送html内容?

java - Spring SFTP集成Session写入方法

java - 为什么我们需要错误类?

java - 如何使用 Mockito 获得一个空的 Stubbing 以进行编程 stub

java - 当按值排序时,compareTo 将 10 设置在 2 之前