In Java, handling exceptions is a crucial part of ensuring robust and error-free code. One common but often misunderstood exception is ClassNotFoundException. This exception occurs when a Java application tries to load a class at runtime but the specified class cannot be found in the classpath.
This blog will cover the ClassNotFoundException in Java, the reason behind its occurrence, and possible solutions.
When the JVM cannot locate a class a Java program refers to, a ClassNotFoundException is raised in Java. The ClassNotFoundException problem can arise for many causes, but it typically indicates that the target class is not on the classpath. Let's dive deep into the blog ClassNotFoundException in Java to learn more about this.
ClassNotFoundException is a subclass of java.lang.Exception in Java. The classNotFoundException in Java, as its name implies, happens when the JVM (Java Virtual Machine) tries to load a specific class but cannot locate it in the classpath you gave. This indicates a broken classpath, a relatively prevalent issue in the Java community.
The ClassNotFoundException most frequently arises when an external dependency is unavailable and results from incorrect application settings. For Java newbies, this issue might be very perplexing.
Another crucial aspect of this exception is that it is a checked exception. If you use methods that may inadvertently raise a ClassNotFoundException in Java, you must explicitly handle the exception using a try-catch block or a throws clause.
Let us see in detail how the ClassNotFoundException in Java occurs.
What Causes ClassNotFoundException in Java?
Several common causes for a ClassNotFoundException to be issued include:
The class is absent from the classpath: This is the most common reason why a ClassNotFoundException occurs. If the class is not on the classpath, the JVM will not be able to locate it.
Class name not matched: Even if a class is on the classpath, the JVM won't be able to detect it if the name is misspelled.
The class comes in a separate package: The JVM won't be able to find the class if it is in a separate package from the one you are attempting to import.
The class is in a JAR file, not on the classpath: If this is the case, the JVM cannot locate the class.
Version compatibility issues: The JVM won't be able to find the class if it isn't in the Java version you are using.
This exception may also be generated if a class is loaded from the classpath but is not available at runtime because some dependencies are missing or if the version of the loaded class and the class at runtime differ.
When the findSystemClass() method is used by the classloader to attempt to load a class.
When utilizing Java's ClassLoader loadClass() function.
Example of Java ClassNotFoundException
The most common example of the ClassNotFoundException in Java is the following:
public class Main { public static void main(String[] args) { try { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "password"); System.out.println("Connection successful to the database"); } catch (ClassNotFoundException e) { System.out.println("Error: JDBC driver not found!"); e.printStackTrace(); } catch (Exception e) { System.out.println("Error: Not able to connect to the database!"); e.printStackTrace(); } } }
You can also try this code with Online Java Compiler
In the above example, the program uses the Class.forName() function to attempt to load the JDBC driver for MySQL. The class of the driver is com.mysql.jdbc.Driver.
A ClassNotFoundException will be issued if this class is not in the classpath. The most frequent reason for this exception is this. It occurs when you try to load the JDBC driver while writing the JDBC connectivity code.
The classpath is missing the MySQL driver jar file in this specific instance of the ClassNotFoundException.
Here, you will see that we utilize the Class.forName ("driver") method to load the driver class contained in a certain jar, in this example, mysql-connector.jar. If the jar is not on the classpath or unavailable to the JVM, it will throw java. lang.ClassNotFoundException: com.mysql.jdbc.Driver.
How to fix the ClassNotFoundException in Java?
The few things which should be followed to fix the ClassNotFoundException in Java are the following:
Thoroughly go over java.lang.ClassNotFoundException stack trace to identify the Java class that was improperly loaded at runtime.
Check if the desired class's name is accurate and if the .jar file's location in your classpath is supplied. If not, you require to add it to the classpath of your application manually.
If it's included in your classpath, there's a reasonable probability that your classpath is overridden or that your application utilizes the classpath supplied in a jar file or start-up script. To resolve this, you need to identify the precise classpath used by your application.
If a third-party class is to blame for the issue, you must first identify it and add the missing.jar files to your classpath.
Now let us see examine frequently asked questions of ClassNotFoundException in Java.
Difference between Classpath and ClassNotFoundException
Basis of Comparison
Classpath
ClassNotFoundException
Definition
A classpath is a list of locations where all the classes are loaded.
ClassNotFoundException is a subclass of java.lang.Exception in Java. The classNotFoundException in Java, as its name implies, happens when the JVM (Java Virtual Machine) tries to load a specific class but cannot locate it in the classpath you gave.
Purpose
Classpath is set in the program so that it can provide the runtime environment with all the classes and third-party libraries attached to it.
A ClassNotFoundException indicates that the Java Virtual Machine searched the entire classpath you gave but could not locate the class you were trying to reference. Checking your classpath thoroughly is the only workable option.
Use-Case scenario
Classpath needs to be set up by the developers so that JVM has all the necessary JAR files and classes during the runtime of the program
The ClassNotFoundException most frequently arises when an external dependency is unavailable and results from incorrect application settings.
Frequently Asked Questions
What is ClassNotFoundException in Java with example?
The ClassNotFoundException in Java is thrown when the Java Virtual Machine (JVM) searches the full classpath but cannot locate the object. The ClassNotFoundException usually arises at runtime because the class is indirectly loaded via Classloader.
How do ClassNotFoundException and ClassdefNotFound differ from one another?
When looking for a class that isn't on the classpath or when looking up a class that isn't on the runtime classpath using an invalid name, a ClassNotFoundException is raised. A NoClassDefFoundError is raised when a compiled class refers to a different class that isn't on the runtime classpath.
What type of exception is ClassNotFoundException?
ClassNotFoundException is a checked exception in Java. This exception is explicitly handled from the code. This is the runtime exception when the JVM cannot locate the class in the classpath.
How to fix Java.lang.ClassNotFoundException: main?
To fix ClassNotFoundException: main, ensure that the class containing the main method is in the classpath. Verify that the correct class name is specified and the compiled .class file is available.
Is ClassNotFoundException checked or unchecked in Java?
ClassNotFoundException is a checked exception in Java. It must be either caught or declared in a method's throws clause because it occurs at runtime when the class loader cannot find the required class.
Conclusion
In this blog, we have discussed about ClassNotFoundException in Java. ClassNotFoundException is a common but manageable issue in Java, often arising from incorrect classpaths or missing dependencies. By understanding its causes, troubleshooting steps, and prevention techniques, developers can effectively address this exception and ensure smoother class loading processes.
If you like to learn more, you can check out our articles: