Ошибка java lang classnotfoundexception

A classpath is a list of locations to load classes from.

These ‘locations’ can either be directories, or jar files.

For directories, the JVM will follow an expected pattern for loading a class. If I have the directory C:/myproject/classes in my classpath, and I attempt to load a class com.mycompany.Foo, it will look under the classes directory for a directory called com, then under that a directory called mycompany, and finally it will look for a file called Foo.class in that directory.

In the second instance, for jar files, it will search the jar file for that class. A jar file is in reality just a zipped collection of directories like the above. If you unzip a jar file, you’ll get a bunch of directories and class files following the pattern above.

So the JVM traverses a classpath from start to finish looking for the definition of the class when it attempts to load the class definition. For example, in the classpath :

C:/myproject/classes;C:/myproject/lib/stuff.jar;C:/myproject/lib/otherstuff.jar

The JVM will attempt to look in the directory classes first, then in stuff.jar and finally in otherstuff.jar.

When you get a ClassNotFoundException, it means the JVM has traversed the entire classpath and not found the class you’ve attempted to reference. The solution, as so often in the Java world, is to check your classpath.

You define a classpath on the command line by saying java -cp and then your classpath. In an IDE such as Eclipse, you’ll have a menu option to specify your classpath.


Эта статья предназначена для начинающих Java, которые в настоящее время сталкиваются с проблемами java.lang.ClassNotFoundException.
Он предоставит вам обзор этого распространенного исключения Java, пример Java-программы для поддержки вашего процесса обучения и стратегии решения.


Если вас интересуют более сложные проблемы, связанные с загрузчиком классов, я рекомендовал вам просмотреть мою серию статей на
java.lang.NoClassDefFoundError,  так как эти исключения Java тесно связаны.

java.lang.ClassNotFoundException: обзор


Согласно документации Oracle,
ClassNotFoundException генерируется  после сбоя вызова загрузки класса с использованием его строкового имени, как показано ниже:

  • Метод Class.forName
  • Метод ClassLoader.findSystemClass
  • Метод ClassLoader.loadClass


Другими словами, это означает, что один конкретный класс Java

не

был
найден или не

мог

быть загружен во время выполнения из загрузчика классов текущего контекста вашего приложения.


Эта проблема может быть особенно запутанной для начинающих Java.
Вот почему я всегда рекомендую разработчикам Java изучать и совершенствовать свои знания о
загрузчиках классов Java . Если вы не вовлечены в динамическую загрузку классов и не используете Java Reflection API, есть вероятность, что ошибка ClassNotFoundException, которую вы получаете, связана не с кодом вашего приложения, а с API-интерфейсом, на который ссылаются. Другая распространенная проблема — неправильная упаковка кода вашего приложения. Мы вернемся к стратегии разрешения в конце статьи.

java.lang.ClassNotFoundException: пример Java-программы


Теперь найдите ниже очень простую Java-программу, которая имитирует 2 наиболее распространенных сценария ClassNotFoundException с помощью Class.forName () и ClassLoader.loadClass ().
Пожалуйста, просто скопируйте / вставьте и запустите программу с IDE по вашему выбору (
Eclipse IDE был использован для этого примера ).


Программа Java позволяет вам выбирать между проблемным сценарием № 1 или проблемным сценарием № 2, как показано ниже.
Просто измените на 1 или 2 в зависимости от сценария, который вы хотите изучить.

 # Class.forName()
private static final int PROBLEM_SCENARIO = 1;

# ClassLoader.loadClass()
private static final int PROBLEM_SCENARIO = 2;

# ClassNotFoundExceptionSimulator

 package org.ph.javaee.training5;

/**
 * ClassNotFoundExceptionSimulator
 * @author Pierre-Hugues Charbonneau
 *
 */
public class ClassNotFoundExceptionSimulator {

       private static final String CLASS_TO_LOAD = "org.ph.javaee.training5.ClassA";
       private static final int PROBLEM_SCENARIO = 1;

       /**
        * @param args
        */
       public static void main(String[] args) {

             System.out.println("java.lang.ClassNotFoundException Simulator - Training 5");
             System.out.println("Author: Pierre-Hugues Charbonneau");
             System.out.println("http://javaeesupportpatterns.blogspot.com");

             switch(PROBLEM_SCENARIO) {

                    // Scenario #1 - Class.forName()
                    case 1:

                           System.out.println("n** Problem scenario #1: Class.forName() **n");
                           try {
                                 Class<?> newClass = Class.forName(CLASS_TO_LOAD);

                                 System.out.println("Class "+newClass+" found successfully!");

                           } catch (ClassNotFoundException ex) {

                                 ex.printStackTrace();

                                 System.out.println("Class "+CLASS_TO_LOAD+" not found!");

                           } catch (Throwable any) {                           
                                 System.out.println("Unexpected error! "+any);
                           }

                           break;

                    // Scenario #2 - ClassLoader.loadClass()
                    case 2:

                           System.out.println("n** Problem scenario #2: ClassLoader.loadClass() **n");                     
                           try {
                                 ClassLoader classLoader = Thread.currentThread().getContextClassLoader();            
                                 Class<?> callerClass = classLoader.loadClass(CLASS_TO_LOAD);

                                 Object newClassAInstance = callerClass.newInstance();

                                 System.out.println("SUCCESS!: "+newClassAInstance);
                           } catch (ClassNotFoundException ex) {

                                 ex.printStackTrace();

                                 System.out.println("Class "+CLASS_TO_LOAD+" not found!");

                           } catch (Throwable any) {                           
                                 System.out.println("Unexpected error! "+any);
                           }

                           break;
             }

             System.out.println("nSimulator done!");
       }
}

# ClassA

 package org.ph.javaee.training5;

/**
 * ClassA
 * @author Pierre-Hugues Charbonneau
 *
 */
public class ClassA {

private final static Class<ClassA> CLAZZ = ClassA.class;

       static {
             System.out.println("Class loading of "+CLAZZ+" from ClassLoader '"+CLAZZ.getClassLoader()+"' in progress...");
       }

       public ClassA() {
             System.out.println("Creating a new instance of "+ClassA.class.getName()+"...");

             doSomething();
       }

       private void doSomething() {           
             // Nothing to do...
       }
}

Если вы запустите программу как есть, вы увидите вывод, как показано ниже для каждого сценария:

Вывод сценария 1 (базовый уровень)

java.lang.ClassNotFoundException Simulator - Training 5
Author: Pierre-Hugues Charbonneau
http://javaeesupportpatterns.blogspot.com

** Problem scenario #1: Class.forName() **

Class loading of class org.ph.javaee.training5.ClassA from ClassLoader 'sun.misc.Launcher$AppClassLoader@bfbdb0' in progress...
Class class org.ph.javaee.training5.ClassA found successfully!

Simulator done!

Вывод сценария 2 (базовый уровень)

java.lang.ClassNotFoundException Simulator - Training 5
Author: Pierre-Hugues Charbonneau
http://javaeesupportpatterns.blogspot.com

** Problem scenario #2: ClassLoader.loadClass() **

Class loading of class org.ph.javaee.training5.ClassA from ClassLoader 'sun.misc.Launcher$AppClassLoader@2a340e' in progress...
Creating a new instance of org.ph.javaee.training5.ClassA...
SUCCESS!: org.ph.javaee.training5.ClassA@6eb38a

Simulator done!


Для «базового» запуска Java-программа может успешно загрузить ClassA.


Теперь давайте добровольно изменим полное имя ClassA и повторно запустим программу для каждого сценария.
Может быть получен следующий вывод:

#ClassA изменен на
ClassB

 private static final String CLASS_TO_LOAD = "org.ph.javaee.training5.ClassB";

# Вывод сценария 1 (проблема репликации)

java.lang.ClassNotFoundException Simulator - Training 5
Author: Pierre-Hugues Charbonneau
http://javaeesupportpatterns.blogspot.com

** Problem scenario #1: Class.forName() **

java.lang.ClassNotFoundException: org.ph.javaee.training5.ClassB
       at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
       at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
       at java.security.AccessController.doPrivileged(Native Method)
       at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
       at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
       at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
       at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
       at java.lang.Class.forName0(Native Method)
       at java.lang.Class.forName(Class.java:186)
       at org.ph.javaee.training5.ClassNotFoundExceptionSimulator.main(ClassNotFoundExceptionSimulator.java:29)
Class org.ph.javaee.training5.ClassB not found!

Simulator done!

Вывод сценария 2 (проблема репликации)

java.lang.ClassNotFoundException Simulator - Training 5
Author: Pierre-Hugues Charbonneau
http://javaeesupportpatterns.blogspot.com

** Problem scenario #2: ClassLoader.loadClass() **

java.lang.ClassNotFoundException: org.ph.javaee.training5.ClassB
       at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
       at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
       at java.security.AccessController.doPrivileged(Native Method)
       at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
       at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
       at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
       at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
       at org.ph.javaee.training5.ClassNotFoundExceptionSimulator.main(ClassNotFoundExceptionSimulator.java:51)
Class org.ph.javaee.training5.ClassB not found!

Simulator done!


Что произошло?
Итак, поскольку мы изменили полное имя класса на org.ph.javaee.training5.ClassB, такой класс не был найден во время выполнения (не существует), что привело к сбою вызовов Class.forName () и ClassLoader.loadClass ().


Вы также можете повторить эту проблему, упаковав каждый класс этой программы в свой собственный JAR-файл, а затем пропустите jar-файл, содержащий ClassA.class, из основного пути к классу. Попробуйте это и посмотрите сами результаты… (подсказка: NoClassDefFoundError)


Теперь давайте перейдем к стратегии разрешения.

java.lang.ClassNotFoundException: стратегии разрешения


Теперь, когда вы понимаете эту проблему, пришло время решить ее.
Разрешение может быть довольно простым или очень сложным в зависимости от первопричины.

  • Не спешите со сложными первопричинами слишком быстро, сначала исключите самые простые причины.
  • Сначала просмотрите трассировку стека java.lang.ClassNotFoundException согласно приведенному выше и определите, какой класс Java не был загружен должным образом во время выполнения, например, код приложения, сторонний API, сам контейнер Java EE и т. Д.
  • Определите вызывающего, например, Java-класс, который вы видите по трассировке стека непосредственно перед вызовами Class.forName () или ClassLoader.loadClass (). Это поможет вам понять, является ли код вашего приложения ошибочным по сравнению с API стороннего производителя.
  • Определите, правильно ли упакован код вашего приложения, например, отсутствуют файлы JAR из вашего classpath
  • Если отсутствующий класс Java отсутствует в коде вашего приложения, то определите, принадлежит ли он стороннему API, который вы используете в соответствии с вашим приложением Java. Как только вы определите его, вам нужно будет добавить отсутствующие JAR-файлы в ваш путь к классам во время выполнения или файл WAR / EAR веб-приложения.
  • Если после нескольких попыток разрешения проблемы все еще не решены, это может означать более сложную проблему иерархии загрузчиков классов. В этом случае, пожалуйста, просмотрите мою серию  статей NoClassDefFoundError для большего количества примеров и стратегий разрешения


Я надеюсь, что эта статья помогла вам понять и вернуться к этому распространенному исключению Java.


Пожалуйста, не стесняйтесь оставлять комментарии или вопросы, если вы все еще боретесь с проблемой java.lang.ClassNotFoundException.

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.

In older days, there are no editors like Eclipse are available. Even in Notepad, people have done java coding and 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” occurs. After the existence of editors like Eclipse, Netbeans, etc., IDE creates a “ClassPath” file kind of entries.

From the above image, we can see that many jar files are present. They are absolutely necessary if the java code wants to interact with MySQL, MongoDB, etc., kind of databases, and also few functionalities need these jar files to be present in the build path. If they are not added, first editors show the errors themselves and provide the option of corrections too.

Implementation: Sample program of connecting to MySQL database and get the contents

Example

Java

import java.sql.*;

public class MySQLConnectivityCheck {

    public static void main(String[] args)

    {

        System.out.println(

            "---------------------------------------------");

        Connection con = null;

        ResultSet res = null;

        try {

            Class.forName("com.mysql.cj.jdbc.Driver");

            con = DriverManager.getConnection(

                "root", "");

            try {

            }

            catch (SQLException s) {

                System.out.println(

                    "SQL statement is not executed!");

            }

        }

        catch (Exception e) {

            e.printStackTrace();

        }

        finally {

            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 

Database  Command Line
MySQL mysql-connector-java-8.0.22.jar
MongoDB mongo-java-driver-3.12.7.jar
SQL Server sqljdbc4.jar
MYSQL sqljdbc.jar
Oracle oracle.jdbc.driver.oracledriver

Note: 

  • When we are developing Web based applications, the jars must be present in ‘WEB-INF/lib directory’.
  • In Maven projects, jar dependency should be present in pom.xml
  • Sample snippet of pom.xml for spring boot

Example 1 With Spring boot

XML

<dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-data-mongodb</artifactId>

</dependency>

Example 2 Without spring boot

XML

<dependency>

    <groupId>org.mongodb</groupId>

    <artifactId>mongodb-driver</artifactId>

    <version>3.6.3</version>

</dependency>

Example 3 Gradle based dependencies (MongoDB) 

XML

dependencies {

      compile 'org.mongodb:mongodb-driver:3.2.2'

  }

Similarly, other DB drivers can be specified in this way. It depends upon the project nature, the dependencies has to be fixed. For ordinary class level projects, all the classes i.e parent class, child class, etc should be available in the classpath. If there are errors, then also .class file will not be created which leads to ClassNotFoundException, and hence in order to get the whole code working, one should correct the errors first by fixing the dependencies. IDE is much helpful to overcome such sort scenarios such as when the program throws ClassNotFoundException, it will provide suggestions to users about the necessity of inclusion of jar files(which contains necessary functionalities like connecting to database.

Last Updated :
30 Sep, 2021

Like Article

Save Article

The java.lang.ClassNotFoundException is a checked exception in Java that occurs when the JVM tries to load a particular class but does not find it in the classpath.

Since the ClassNotFoundException is a checked exception, it must be explicitly handled in methods which can throw this exception — either by using a try-catch block or by throwing it using the throws clause.

Install the Java SDK to identify and fix exceptions

What Causes ClassNotFoundException in Java

Common causes of the java.lang.ClassNotFoundException are using the following methods to load a class:

  • Class.forName()
  • ClassLoader.findSystemClass()
  • ClassLoader.loadClass()

In all the above cases, the class attempted to be loaded is not found on the classpath, leading to the ClassNotFoundException in Java.

ClassNotFoundException in Java Example

A very common example of ClassNotFoundException is when a JDBC driver is attempted to be loaded using Class.forName() and the driver’s JAR file is not present in the classpath:

public class ClassNotFoundExceptionExample {
    private static final String DRIVER_CLASS = "com.mysql.jdbc.Driver";

        public static void main(String[]  args) throws Exception {
                System.out.println("Loading MySQL JDBC driver");
                Class.forName(DRIVER_CLASS);
        }
            }

Since the MySQL JDBC driver JAR file is not present in the classpath, running the above code leads to a java.lang.ClassNotFoundException:

Loading MySQL JDBC driver
Exception in thread "main" java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:602)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
    at java.base/java.lang.Class.forName0(Native Method)
    at java.base/java.lang.Class.forName(Class.java:340)
    at ClassNotFoundExceptionExample.main(ClassNotFoundExceptionExample.java:6)

To fix the Java exception, the mysql-connector JAR should be included in the application classpath.

How to Resolve ClassNotFoundException in Java

The following steps should be followed to resolve a ClassNotFoundException in Java:

  1. Find out which JAR file contains the problematic Java class. For example, in the case of com.mysql.jdbc.driver, the JAR file that contains it is mysql-connector-java.jar.
  2. Check whether this JAR is present in the application classpath. If not, the JAR should be added to the classpath in Java and the application should be recompiled.
  3. If that JAR is already present in the classpath, make sure the classpath is not overridden (e.g. by a start-up script). After finding out the exact Java classpath used by the application, the JAR file should be added to it.

To fix the Java exception, the mysql-connector JAR should be included in the application classpath.

Track, Analyze and Manage Java Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates Java error monitoring and triaging, making fixing errors easier than ever. Try it today.

What is ClassNotFoundException in Java
ClassNotFoundException is one of Java nightmare every Java developer face in there day to day life. java.lang.NoClassDefFoundError and java.lang.ClassNotFoundException are two errors  which occurs by and now and chew up of your precious time while finding and fixing root cause. From the name java.lang.ClassNotFoundException looks quite simple but underlying cause of it is always different and which classifies it as an environmental issue. In this java tutorial, we will see what is ClassNotFoundException in java, what is real cause of it, and how to fix it along with some more frequent and infamous examples of java.lang.ClassNotFoundException in Java or J2EE, Don’t mistake this exception with NoClassDefFoundError in Java which is also due to incorrect classpath in Java. 


Though both of them are related to missing class file when Java tries to load class in Java they are completely different to each other.  Correct understanding of  When class is loaded in Java and How Classpath works  is must to troubleshoot and fix this error quickly.



What is java.lang.classNotFoundException in Java

As the name suggests classNotFoundException in Java is a subclass of java.lang.Exception and Comes when Java Virtual Machine tries to load a particular class and doesn’t found the requested class in classpath. 


Another important point about this Exception is that, It is a checked Exception and you need to provide explicitly Exception handling while using methods which can possibly throw classnotfoundexception in java either by using try-catch block or by using throws clause. 


Though underlying concept of this exception is simple but it always manifest itself in such format that you need to spend some time to figure out what exactly wrong with your classpath. If you want to know nasty secrets of java classpath  which can cause issue see the link

When ClassNotFoundException occurs in Java:


As per java doc java.lang.classNotFoundException comes in following cases:


1) When we try to load a class by using Class.forName() method and .class file or binary of class is not available in classpath.
2) When Classloader try to load a class by using findSystemClass () method.
3) While using loadClass() method of class ClassLoader in Java.

What is ClassNotFoundException in Java - Fix SolutionThese statements are completely true in terms of theory of ClassNotFoundExcepiton in Java but as per my experience the concept is «ClassNotFoundException will come only when JVM tries to load a class at run-time, nothing related to compile time unlike NoClassDefFoundError«. 


Also since till run time JVM doesn’t know about this Class, it can only be done by above-specified method or by employing Reflection to read the name of class from some configuration file like in case of struts its struts-config.xml file and then load the class specified on those configuration files. Reflection is the great power of Java but you need to be aware of java.lang.classNotFoundException while using it or loading class in Java. See Understanding the Java Virtual Machine: Class Loading and Reflection to learn more about how exactly class loading works inside JVM.

Examples of classnotfoundexception in java

Though java.lang.classNotFoundException is very common and it can come for any classes, I usually see it while doing JDBC connectivity like when I was writing Java program to connect Oracle database. I am going to list some of the most common scenario where you will get classnotfoundexception in java.

1. java.lang.classnotfoundexception com.mysql.jdbc.driver


This is a classical and most infamous example of and also my first encounter with java.lang.ClassNotFoundException and comes when you are writing JDBC connectivity code and trying to load the JDBC driver. In this particular case of ClassNotFoundException looks like MySQL driver jar file is missing from Classpath. 



If you pay attention you will find that we use method Class.forName (“driver”) to load the driver class which resides in a particular jar in case of this its mysql-connector.jar and if that jar is not in the classpath or not accessible to JVM it will throw  java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

Here are few more infamous examples of java.lang.ClassnotFoundException which comes here and there while doing any Java J2EE project. 

java.lang.classnotfoundexception org.hibernate.hql.ast.hqltoken

java.lang.classnotfoundexception org.springframework.web.context.contextloaderlistener

java.lang.classnotfoundexception org.eclipse.core.runtime.adaptor.eclipsestarter

java.lang.classnotfoundexception org.apache.catalina.startup.catalina

java.lang.classnotfoundexception javax.mail.messagingexception

java.lang.classnotfoundexception oracle.jdbc.driver.oracledriver

This ClassNotfoundException comes when you are trying to connect Oracle database from Java program using JDBC but you don’t have corresponding Oracle driver e.g.ojdbc6.jar is not in classpath of your Java program

2. More Complicated ClassNotFoundException

With the advent of dynamic library e.g. OSGi and ClassLoader in Java, this exception can be more tricky and hard to find. Thanks to Mr. Anonymous who has summarized this beautifully, here it is what he says“It can become a bit more complicated than that. 



In truth, a class does not have to be just visible by the JVM through its classpath but be visible by the Classloader being used. When you are in a multi-classloader environment (In a EE environment, for example, but not limited to), each classloader may have its own rules to search for the classes, and this behavior might depend on the dynamic hierarchy of the Classloaders.



For example, in a project that uses an EAR packaging with WARs inside it, libraries in the lib folder of the EAR are visible to classes inside a WAR, but any classes packaged in a jar put in the WEB-INF/lib on the WAR cannot be seen by classes in different modules (other WARs, EJB-JARS, etc).



It can get really complicated as its common for different modules depending on different versions of the same libraries as different modules depend on each other. It can be a challenge to manage this. Sometimes the classloader can see multiple versions of the same class; sometimes they can see no version at all. 


Sometimes different dependency paths end in different versions of the same class. And many of these cases end in a ClassNotFoundException.

How to fix java.lang.ClassNotFoundException in Java


As you have seen from above examples its clear problem of classpath, so here is
my approach to fix or resolve java.lang.ClassNotFoundException:

1) First find out the jar file on which problematic class file is present for example in case of «

com.mysql.jdbc.driver» its mysql-connector-java.jar. If you don’t know how to find which jar file a particular class you can see eclipse shortcuts to do that or you can simply do «Ctrl+T» in Eclipse and type the name of class, It will list all the jar in the order they appear in eclipse classpath.

2) Check whether your classpath contains that jar, if your classpath doesn’t contain the jar then just add that class in your classpath.

3) If it’s present in your classpath then there is high chance that your classpath is getting overridden or application is using classpath specified in jar file or start-up script and to fix that you need to find the exact classpath used by your application.

Live example of reproducing and Fixing ClassNotFoundException in java


I think if we are able to reproduce and solve certain problem we become more comfortable dealing with that, that’s why here we will reproduce java.lang.ClassNotFoundException and solve it by following the concept we have discussed so far.

1)

Create a Class called StockTrading.java

public class StockTrading{
   public String getDescription(){
   return «StockTrading»;
  }
}

2)

create a Class called OnlineStockTranding.java and load the class StockTrading.java as Class.forName («stocktrading»);

public class OnlineStockTrading {
   public static void main(String args[]) throws ClassNotFoundException{
      Class.forName(«StockTrading»);
      System.out.println(«StockTrading class successfully loaded»);
   }
}

3) Compile both Java source file which will create two class files and run the program should run fine.

javin@trading~/java:

javac *.java

javin@trading ~/java:

ls –lrt
-rw-r—r— 1 javin None  90 Aug 21 09:27 StockTrading.java
-rw-r—r— 1 javin None 208 Aug 21 09:28 OnlineStockTrading.java
-rwxr-xr-x 1 javin None 282 Aug 21 09:28 StockTrading.class
-rwxr-xr-x 1 javin None 638 Aug 21 09:28 OnlineStockTrading.class

javin@trading ~/java:$

java OnlineStockTrading
StockTrading class successfully loaded

4) Now just

remove the .class file for stocktrading.java and run the Java program and it will throw java.lang.ClassNotFoundException in java.

javin@trading ~/java:

rm StockTrading.class

javin@trading ~/java:

java OnlineStockTrading
Exception in thread «main» java.lang.ClassNotFoundException: StockTrading
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)

ClassFoundException vs NoClassDefFoundError vs UnSupportedClassVersionError


There are lots of exceptions in java but these three are the one who most haunted the java developer most mainly because these three are mostly related to environment issues and they all depends upon JVM and Classpath behaviour. Though they look similar there is slight difference between ClassFoundException and NoClassDefFoundError and UnSupportedClassVersionError and we will highlight those differences here for easy understanding and differentiating these three:

1)

ClassNotFoundException comes on Runtime when requested class is not available in classpath and mainly due to call to Class.forName () or Classloader.loadClass () or ClassLoader.findSystemClass ().

2)

NoClassDefFoundError comes when problematic class was present when your compiled your application but they are not in classpath while you running your program.

3)

UnSupportedClassVersionError is easy to differentiate because it’s related to version of classpath and usually comes when you compile your code in higher Java version and try to run on lower java version. Can be resolved simply by using one java version for compiling and running your application.

So that’s all on

ClassNotFoundException in java for now , please let me know if you have any tip or  any personal experience on solving java.lang.ClassNotFoundException in Java which you would like to share.

Some more Interesting tutorials:

Понравилась статья? Поделить с друзьями:
  • Ошибка java home
  • Ошибка java dll
  • Ошибка java cristalix
  • Ошибка java connect
  • Ошибка java class interface or enum expected