【发布时间】:2014-08-16 12:22:23
【问题描述】:
请检查以下代码.... 类 testError 已被实例化,但仍然生成 Class not found 异常...如果是这样,那么为什么写在异常处理程序中的语句没有被打印?
class testError
{
void display()
{
System.out.println("This is testError Class");
}
}
class checkResult
{
public static void main(String[] args)
{
testError te = new testError();
te.display();// I hope the class has been created
Class cls = Class.forName("testError"); // will throw ClassNotFound exception
// Why??... Though the class has been
// instantiated
// if we try to put it in trycatch block it will work...Why??
try{ Class cls = Class.forName("testError");}
catch(ClassNotFoundException e)
{
System.out.println("Error found"); //"Error found" will not be printed
// as the class has been instantiated
}
}
}
【问题讨论】:
-
猜这是Java?您需要传递完全限定的类名。请参阅文档:docs.oracle.com/javase/7/docs/api/java/lang/…
-
这些类真的在默认包中,还是在您定义的某个包中?
-
嗨..这是在默认包中..问题是类已被实例化,ergo将在类路径中,但如果尝试执行代码,则会抛出未找到类的异常......
-
hii rparree....如果完整的类名是原因,那么 try catch 块中也会出现错误..但它的工作正常
-
第一个
Class.forName("testError");真的会抛出CNFException吗?还是 Java 只是抱怨您应该捕获此异常 - 因为在此之前您不会捕获或抛出任何异常?对于第二种情况,您可能应该阅读something about exception types in Java,然后查看Class.forName(...)method
标签: java classnotfound