Reputation: 3738
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?
Upvotes: 0
Views: 1912
Reputation: 3780
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
}
}
Upvotes: 2