我有以下代码:
class ClassDetails {
private String current_class;
public ClassDetails(String current_class) {
this.current_class = current_class;
}
public void getClassDetails() throws ClassNotFoundException {
try {
Class theClass = Class.forName(current_class);
String name = theClass.getName() ;
System.out.println(name);
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
}
}
class MMain {
public static void main(String[] args) {
ClassDetails C = new ClassDetails(args[0]);
C.getClassDetails();
}
}
在main中出现了这个错误:
Unhandled exception type ClassNotFoundException
我该如何解决这个问题?
您的main
方法调用getClassDetails()
方法,该方法抛出异常,如签名所示:
public void getClassDetails() throws ClassNotFoundException
并且您没有捕获它,或者在方法中抛出它,因此您的代码将无法编译。所以你必须这样做:
public static void main(String[] args) throws ClassNotFoundException {
ClassDetails C = new ClassDetails(args[0]);
C.getClassDetails();
}
或:
public static void main(String[] args) {
ClassDetails C = new ClassDetails(args[0]);
try
{
C.getClassDetails();
}
catch(ClassNotFoundException ex)
{
//Add exception handling here
}
}