ClassNotFoundException in Java Example
Example: Sample program of connecting to MySQL database and get the contents
Java
// Java Program to check for MySQL connectivity Issue // Importing database (SQL) libraries import java.sql.*; // Main Class public class MySQLConnectivityCheck { public static void main(String[] args) { // Display message for better readability System.out.println( "---------------------------------------------" ); // Initially setting connection object // and result set to null Connection con = null ; ResultSet res = null ; // Try block to check for exceptions try { // We need to have mysql-connector-java-8.0.22 // or relevant jars in build path of project // Loading drivers // This driver is the latest one Class.forName( "com.mysql.cj.jdbc.Driver" ); con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/test?serverTimezone=UTC" , "root" , "" ); // Try block to check for exceptions try { // Set of statements to be checked } // Catch block 1 catch (SQLException s) { // Display message when SQLException is // encountered System.out.println( "SQL statement is not executed!" ); } } catch (Exception e) { // In case of general Exception // print and display the line number where the // exception occurred e.printStackTrace(); } finally { // Finally for all cases indirectly closing the // connections & making the resultset and // connection object to null res = null ; con = null ; } } } |
Output
Case 1: In the above code, we are using com.mysql.cj.jdbc.Driver and in that case if we are not having mysql-connector-java-8.0.22.jar, then we will be getting ClassNotFoundException.
Case 2: So, keep the jar in the build path as shown below.
Note: Similarly for any database connectivity, we need to have the respective jars for connecting to that database. The list of database driver jars required by java to overcome ClassNotFoundException is given below in a tabular format
How to Solve java.lang.ClassNotFoundException in Java?
In Java, java.lang.ClassNotFoundException is a checked exception and occurs when the Java Virtual Machine (JVM) tries to load a particular class and the specified class cannot be found in the classpath. ClassNotFoundException should be handled with a try-catch block or using the throw keyword.
In older days, there are no editors like Eclipse are available. Even in Notepad, people have done Java coding by using the “javac” command to compile the Java files, and they will create a ‘.class’ file. Sometimes accidentally the generated class files might be lost or set in different locations and hence there are a lot of chances of ClassNotFoundException occurring. After the existence of editors like Eclipse, Netbeans, etc., IDE creates a ClassPath file kind of entry.
Contact Us