0

我有以下代码:

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();
  }
}

我主要有这个错误:

Unhandled exception type ClassNotFoundException

我该如何解决这个问题?

4

1 回答 1

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
      }
}
于 2013-03-24T13:05:08.317 回答