What is a Java ClassNotFoundException?

Java Exception FAQ: What is a ClassNotFoundException?

Answer: A ClassNotFoundException can happen when you use Java's Reflection capability to dynamically create a class. Here's some example code where I intentionally throw a ClassNotFoundException by trying to create and use a class ("FooClass") that I know doesn't exist:

package com.devdaily.javasamples;

import java.lang.reflect.Method;

public class JavaReflectionExample1

  public JavaReflectionExample1()
    Class c;
      c = Class.forName("FooClass");
      Method m[] = c.getDeclaredMethods();
    catch (ClassNotFoundException e)
      // deal with the exception here ...

  public static void main(String[] args)
    new JavaReflectionExample1();


Because that class doesn't exist, when I try to run this program I get the following Java error message (stack trace):

java.lang.ClassNotFoundException: FooClass
   at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
   at java.security.AccessController.doPrivileged(Native Method)
   at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
   at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
   at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268)
   at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
   at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
   at java.lang.Class.forName0(Native Method)
   at java.lang.Class.forName(Class.java:164)
   at com.devdaily.javasamples.JavaReflectionExample1.(JavaReflectionExample1.java:13)
   at com.devdaily.javasamples.JavaReflectionExample1.main(JavaReflectionExample1.java:26)

Share it!

There’s just one person behind this website; if this article was helpful (or interesting), I’d appreciate it if you’d share it. Thanks, Al.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.