Skip to main content Skip to docs navigation
TechSpiderTutorials

java.lang.ClassNotFoundException in Java

On this page

Java.lang.ClassNotFoundException Class

Creating Objects

Default Constructor: This creates an instance without a message.

ClassNotFoundException ex1 = new ClassNotFoundException();

Constructor with Message:passing a custom error message.

ClassNotFoundException ex2 = new ClassNotFoundException("Custom error message");

ClassNotFoundException Class Example

public class ClassNotFoundExceptionExample {
    public static void main(String[] args) {
        // Class that does not exist
        String className = "com.example.NonExistentClass"; 
        try {
            // Attempt to load a class that doesn't exist
            Class<?> cls = Class.forName(className);
            System.out.println("Class " + cls.getName() + " found successfully.");
        } catch (ClassNotFoundException e) {
            // Handle the exception
            System.out.println("Error: Class " + className + " not found!");
        } finally {
            System.out.println("Execution completed.");
        }
    }
}

Output:

Error: Class com.example.NonExistentClass not found!
                    Execution completed.