java - 我们可以将 Exception 类对象分配给 Object 类对象的引用吗

标签 java class object

为什么这行不通,任何人都可以给出确切的答案....

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/

相关文章:

java - 如何仅在其中一个类完成测试后才以类级并行性运行测试

java - Web 服务与 Servlet

javascript - javascript中将实例移动到另一个类的方法

java - 您在此代码/程序中发现什么错误?错误是除非您先输入数字,否则它不会运行

JavaScript 对象 : use a variable's value to access a specific object

netbeans - Java 结果 : 143

java - Mysql类未找到异常

c++ - 在另一个程序中使用一个程序中的变量

java - NetBeans - 找不到主类

javascript - 将数组对象字段数据添加到 JavaScript 中的单个对象中