I have the following code:

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

And I have this error in main:

Unhandled exception type ClassNotFoundException

How can I solve this?

有帮助吗?

解决方案

Your main method calls the getClassDetails() method, which throws that exception, as the signature shows:

public void getClassDetails() throws ClassNotFoundException

And you aren't catching it, or throwing it in the method, so your code will not compile. So you must either do:

public static void main(String[] args) throws ClassNotFoundException {
    ClassDetails C = new ClassDetails(args[0]);
    C.getClassDetails();
}

Or:

public static void main(String[] args) {
    ClassDetails C = new ClassDetails(args[0]);
      try
      {
          C.getClassDetails();
      }
      catch(ClassNotFoundException ex)
      {
          //Add exception handling here
      }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top