我有以下代码:
class Exception
{
public static void main(String args[])
{
int x = 10;
int y = 0;
int result;
try{
result = x / y;
}
catch(ArithmeticException e){
System.out.println("Throwing the exception");
throw new ArithmeticException();
}
}
}
类的名称是“Exception”。这与默认导入到程序中的 java.lang.Exception 相同。那么为什么这个程序编译时会使用两个实际上具有相同名称的类呢?
最佳答案
Why does this program compile with two classes having effectively the same name?
它们有相同的简单名称。但是,它们的名称(完全限定名称,包括包声明)不同。
按照您定义的方式,您的代码无法编译,除非您的类位于项目的默认包中。您的类型(Exception
)隐藏了 java.lang
包中定义的类型,并且由于您的类型不是 Throwable
的子类型,因此编译器引发错误:
No exception of type
Exception
can be thrown; an exception type must be a subclass ofThrowable
如果您想指定应捕获 java.lang.Exception
,则必须使用完全限定名称,否则会出现命名冲突:
class Exception {
public static void main(String args[]) {
int x = 10;
int y = 0;
int result;
try {
result = x / y;
} catch (ArithmeticException e) {
System.out.println("Throwing the exception");
throw new ArithmeticException();
} catch (java.lang.Exception ae) {
System.out.println("Caught the rethrown exception");
}
}
}
关于java - 为什么Java允许类名与它导入的类名相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33932619/