我有以下代码:
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
我该如何解决这个问题?
答案 0 :(得分:2)
您的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
}
}