How to instantiate class from with class.forName()

Unhandled exception type ClassNotFoundException

That means the compiler is expecting you to surround the class loading function(s) with an exception handling block. Namely, the try and catch blocks.

At a minimum, you could do something like this:

try {
  // load class by name, etc.
}
catch(Exception ex)
{
  println("Something went wrong");
  println(ex.toString());
}

Of course, that will print the same message (plus the built-in) for any error.

The message you are getting is calling out for something more like this:

try {
  // load class by name, etc.
}
catch(ClassNotFoundException ex)
{
  println("Class not found");
}
catch(IllegalAccessException ex)
{
  println("Do you have permission for that?");
}
catch(InstantiationException ex)
{
  println("Could not instantiate object");
}

It is up to you how much detail you want from the exception handling.

For more, take a look at Lesson: Exceptions (The Java™ Tutorials > Essential Java Classes)

1 Like