为什么这行不通,任何人都可以给出确切的答案....
public class Manager
{
public static void main(String args[])
{
try{
Object obj=new A(); //it will generate ClassNotFoundException object
System.out.println("currently the reference obj is pointer to the object:"+obj);
}catch(Object o)
{
System.out.println(o);
}
}
System.out.println("End of Main");
}
最佳答案
这不会起作用,因为“catch”语句中声明的变量必须是异常类型(即 Throwable
或子类型)。
来自section 14.20 Java 语言规范:
A catch clause must have exactly one parameter (which is called an exception parameter); the declared type of the exception parameter must be the class Throwable or a subclass (not just a subtype) of Throwable, or a compile-time error occurs.In particular, it is a compile-time error if the declared type of the exception parameter is a type variable (§4.4). The scope of the parameter variable is the Block of the catch clause.
当然你可以写:
catch(Throwable t)
{
Object o = t;
System.out.println(o);
}
目前尚不清楚您为什么要这样做。
关于java - 我们可以将 Exception 类对象分配给 Object 类对象的引用吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3414837/