why this is will not work, can any one give the exact answer for this one....
public class Manager
{
public static void main(String args[])
{
try{
Object obj=new A(); //it will generate ClassNotFoundException object
开发者_如何学GoSystem.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");
}
That won't work simply because the variable declared in the "catch" statement has to be an exception type (i.e. Throwable
or a subtype).
From section 14.20 of the Java Language Specification:
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.
Of course you could write:
catch(Throwable t)
{
Object o = t;
System.out.println(o);
}
It's not clear why you'd want to though.
You said nothing about class A's constructor... Is it actually throwing an exception ? If yes, then the other answers should help you out. If no, then perhaps I might recall that instanciating an exception is not throwing an exception...
Examples :
This won't work :
try {
new Exception();
} catch (Exception e) {
System.out.println("This will never be printed...");
}
However you can get the intended result by adding the throw
keyword :
try {
throw new Exception();
} catch (Exception e) {
System.out.println("This will actually be printed...");
}
精彩评论