Java反射 - 错误抛出

时间:2013-03-24 13:01:52

标签: java exception reflection throws

我有以下代码:

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

我该如何解决这个问题?

1 个答案:

答案 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
      }
}