gpt4 book ai didi

java - Java中的内部静态与非静态异常类

转载 作者:行者123 更新时间:2023-12-04 21:01:28 29 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Making the inner class of a generic class extend Throwable [duplicate]

(1 个回答)


1年前关闭。




我确实注意到有关静态和非静态内部异常类的奇怪行为。

例如下面的代码不会编译:

public class MyClass<T> {
private class MyInnerException extends Exception { // won't compile
..
}
}

但下面的代码将编译:
public class MyClass<T> {
private static class MyInnerException extends Exception { // will compile
..
}
}

为什么会这样?

有一点是肯定的,由于类型删除,我们不能有泛型异常,但是上面的不是泛型异常类,而是在泛型类中。但是如果它是静态的它是允许的,但如果它是非静态的它是不允许的?

后续问题,是否因为 Generic 的类型删除功能而不允许泛型异常,就像这里提到的:
https://www.mscharhag.com/java/java-exceptions-and-generic-types
还是有其他原因?

最佳答案

One thing is for sure that we cannot have Generic exceptions due to type erasure but then the above is not a Generic exception class but it is inside the Generic class.


你的内部类(第一个片段) 泛型类,因为它的封闭类是泛型类,而封闭类是内部类的一部分。如果没有相应的封闭类实例,则无法创建内部类的实例。
至于为什么泛型类不能扩展 Exception :

It is a compile-time error if a generic class is a direct or indirect subclass of Throwable (§11.1.1).

This restriction is needed since the catch mechanism of the Java Virtual Machine works only with non-generic classes.


( JLS 8.1.2 )
即 catch 子句无法区分 MyClass<String>.MyInnerExceptionMyClass<Integer>.MyInnerException ,因此不允许通用异常类。

关于java - Java中的内部静态与非静态异常类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59390612/

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