Java : ClassNotFoundException with Examples

ClassNotFoundException (Java SE 21 & JDK 21) with Examples.
You will find code examples on most ClassNotFoundException methods.


Summary

Thrown when an application tries to load in a class through its string name using: The forName method in class Class. The findSystemClass method in class ClassLoader . The loadClass method in class ClassLoader.

Class diagram

public class Foo {
}
public class Main {
    public static void main(String[] args) {
        try {
            // A Foo class exists.
            final var foo = Class.forName("Foo");
            System.out.println("foo : " + foo);

            // A Bar class does not exist.
            final var bar = Class.forName("Bar");

        } catch (ClassNotFoundException e) {
            System.out.println("ClassNotFoundException! : " + e.getMessage());
        }
    }
}

// Result
// ↓
//> java Main
//foo : class Foo
//ClassNotFoundException! : Bar

Constructors

ClassNotFoundException ()

Constructs a ClassNotFoundException with no detail message.

final var e = new ClassNotFoundException();
System.out.println(e); // java.lang.ClassNotFoundException

ClassNotFoundException (String s)

Constructs a ClassNotFoundException with the specified detail message.

final var e = new ClassNotFoundException("abcde");
System.out.println(e); // java.lang.ClassNotFoundException: abcde
System.out.println(e.getMessage()); // abcde

ClassNotFoundException (String s, Throwable ex)

Constructs a ClassNotFoundException with the specified detail message and optional exception that was raised while loading the class.

final var ex = new ClassNotFoundException("XYZ");
final var e = new ClassNotFoundException("abc", ex);
System.out.println(e); // java.lang.ClassNotFoundException: abc
System.out.println(e.getMessage()); // abc

System.out.println(e.getException()); // java.lang.ClassNotFoundException: XYZ
System.out.println(e.getException().getMessage()); // XYZ

Methods

Throwable getException ()

Returns the exception that was raised if an error occurred while attempting to load the class.

final var ex = new ClassNotFoundException("XYZ");
final var e = new ClassNotFoundException("abc", ex);
System.out.println(e); // java.lang.ClassNotFoundException: abc
System.out.println(e.getMessage()); // abc

System.out.println(e.getException()); // java.lang.ClassNotFoundException: XYZ
System.out.println(e.getException().getMessage()); // XYZ

Methods declared in Throwable

addSuppressed, fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, getSuppressed, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString

Please see the link below.


Related posts

To top of page