Java lang classnotfoundexception ошибка

The Java ClassNotFoundException occurs when the JVM tries to load a class but does not find it in the classpath. Learn the three steps you can take to fix it.

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

![Rollbar in action](https://rollbar.com/wp-content/uploads/2022/04/section-1-real-time-errors@2x-1-300×202.png)

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.

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.


Эта статья предназначена для начинающих 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.

In this tutorial, we will discuss the java.lang.classnotfoundexception – ClassNotFoundException. This exception is thrown when an application tries to load a class through its string name, but no definition for the specified class name could be found. A class can be loaded using one of the following methods:

  • The forName method that resides inside the Class class.
  • The findSystemClass method that resides inside the ClassLoader class.
  • The loadClass method that resides inside the ClassLoader class.

You can also check this tutorial in the following video:

java.lang.ClassNotFoundException Example – How to handle java.lang.ClassNotFoundException
java.lang.classnotfoundexception

This exception java.lang.classnotfoundexception extends the ReflectiveOperationException, which is defined as the common superclass of exceptions thrown by reflective operations in core reflection. Finally, after the Java 1.4 release, the ClassNotFoundException has been retrofitted to conform to the general purpose exception-chaining mechanism. The raising exception may be accessed via the Throwable.getCause() method.

1. The java.lang.ClassNotFoundException in Java

The java.lang.ClassNotFoundException is thrown when the Java Virtual Machine (JVM) tries to load a particular class and the specified class cannot be found in the classpath. The Java ClassNotFoundException is a checked exception and thus, must be declared in a method or constructor’s throws clause.

The following example tries to load a class using the forName method. However, the specified class name cannot be found and thus, a ClassNotFoundException is thrown.ClassNotFoundExceptionDemo.java

/**
 * @author Santosh Balgar Sachchidananda
 * This class tries to load MySQL driver. For the demo of ClassNotFoundexception
 * I haven't added the jar file in classpath. Add the mysql-connector jar in classpath
 * to fix this exception
 */
public class ClassNotFoundExceptionDemo {
    private static final String DRIVER_CLASS = "com.mysql.jdbc.Driver";

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

A sample execution is shown below:

Exception in thread "main" java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
	at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
	at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
	at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
	at java.base/java.lang.Class.forName0(Native Method)
	at java.base/java.lang.Class.forName(Class.java:315)
	at com.jcg.ClassNotFoundExceptionDemo.main(ClassNotFoundExceptionDemo.java:14)

To fix the exception download the mysql-connector jar from Oracle website and include in your class path.

Above scenario is the most common scenario when CLassNotFoundException is raised. However, it can become bit ugly or messy sometimes in a complex web deployment environments. Suppose your application is deployed as an EAR and it contains multiple jar and WAR files, it can sometimes raise this exception because of class visibility issues. Jar files and class files under EAR’s lib folder are visible to classes in WAR file, however jars and classes under war file’s lib folder can’t be seen by other modules or jars. It becomes even messier when different modules involved refer to different versions of same jar file. You need to be careful when such inter-dependencies exist.

2. How to deal with the java.lang.ClassNotFoundException

  • Verify that the name of the requested class is correct and that the appropriate .jar file exists in your classpath. If not, you must explicitly add it to your application’s classpath.
  • In case the specified .jar file exists in your classpath then, your application’s classpath is getting overridden and you must find the exact classpath used by your application.
  • In case the exception is caused by a third party class, you must identify the class that throws the exception and then, add the missing .jar files in your classpath.

Below is the simple example to illustrate ClassNotFoundException and a way to fix it.

MainClass is dependent on DependentClass for the successful execution, if everything is there as expected then you will see below output,

Hello from main class
Loading dependent class
Hello From Dependent Class
Dependent class loaded successfully

For the demo purpose, I have removed DependentClass.class from the output directory. Now if you try to run the MainClass you get below output,

Hello from main class
Loading dependent class
Exception in thread "main" java.lang.NoClassDefFoundError: com/jcg/DependentClass
	at com.jcg.MainClass.main(MainClass.java:7)
Caused by: java.lang.ClassNotFoundException: com.jcg.DependentClass
	at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
	at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
	at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
	... 1 more

To fix this we need to make DependentClass.class available. This can be done by rebuilding the project in our case. Otherwise you need to verify the classes and libraries in your class path and fix the same.

Below is the code for our example,DependentClass.java

public class DependentClass {
    public void sayHello() {
        System.out.println("Hello From Dependent Class");
    }
}

MainClass.java

public class MainClass {
    public static void main(String[] args) {
        System.out.println("Hello from main class");
        System.out.println("Loading dependent class");
        DependentClass dClass = new DependentClass();
        dClass.sayHello();
        System.out.println("Dependent class loaded successfully");
    }
}

3. ClassNotFoundException vs NoClassDefFoundError vs UnSupportedClassVersionError

ClassNotFoundException is generally thrown when you try to load a class using Class.forname or loadClass and findSytemClass methods in ClassLoader methods, the class you are trying to load is not present in the Classpath. Another scenario when it can happen is the class you are trying to load is not a valid class.

NoClassDefFoundError is an error and it occurs when a class is present at compile-time and the same is missing at the run time. This is a fatal error and happens when you try to instantiate class or when you try to call a static method.

UnSupportedClassVersionEorror this error happens when the class is compiled with a higher JDK version than the one used for execution. When you encounter this error, verify the installed Java version and the Java path set in the JAVA_HOME environment variable.

4. More articles

  • java.lang.StackOverflowError – How to solve StackOverflowError
  • Unreachable Statement Java Error – How to resolve it
  • java.lang.NullPointerException Example – How to handle Java Null Pointer Exception (with video)
  • Try Catch Java Example
  • Java Constructor Example (with video)
  • Online Java Compiler – What options are there
  • What is null in Java

5. Download the source code

For the demo program, I have used IntelliJ Idea IDE and Java 11 version.

Last updated on Jul. 23rd, 2021

  1. HowTo
  2. Java Howtos
  3. Exception in Thread Main …
  1. the java.lang.ClassNotFoundException Error in Java
  2. Causes of java.lang.ClassNotFoundException in Intellij IDEA
  3. Solution to java.lang.ClassNotFoundException in Intellij IDEA

Exception in Thread Main Java.Lang.ClassNotFoundException in IntelliJ IDEA

Today’s tutorial will discuss potential reasons for the java.lang.ClassNotFoundException whenever a Java program’s main method is executed.

the java.lang.ClassNotFoundException Error in Java

java.lang.ClassNotFoundException is triggered if the ClassLoader cannot find the class in its system. In the JVM (Java Virtual Machine) core library, ClassLoader is used to load and locate a class.

This error is thrown by ClassLoader if it cannot load a class from the application library.

In addition, you should be aware of the checked nature of this exception and the necessity to properly handle it when calling methods that can trigger the java.lang.ClassNotFoundException in Java, whether via a try-catch block or the throws condition.

Let’s have an example to understand better which throws java.lang.ClassNotFoundException in Java on Intellij IDEA 14.0. After that, we’ll discuss its causes and solution.

In this example, we constructed a basic Hello Programers! program. It’s producing incorrect output; hence, the java.lang.ClassNotFoundException exception will be triggered.

public class Hello {
  public static void main(String[] args) {
    System.out.println("Hello Programers!");
  }
}

Output:

Exception in thread "main" java.lang.ClassNotFoundException: Hello
at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:260)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:116)

Causes of java.lang.ClassNotFoundException in Intellij IDEA

The following are some of the factors that result in this exception:

  1. When we attempt to load a class by utilizing the class’s binary, we discover that it is not present in the classpath.
  2. If we use the loadClass() function of the ClassLoader class in Java.
  3. The java.lang.ClassNotFoundException occurs when the Java Virtual Machine attempts to load a class during runtime.

Solution to java.lang.ClassNotFoundException in Intellij IDEA

This is simply a problem with the Intellij IDEA. Therefore, please follow the steps below to fix it:

  • Launch IntelliJ IDEA first, and then simultaneously press Ctrl, Shift, Alt and s to open the Project Settings window.
  • On the left panel, select modules, then expand your_project_name, and finally go to (your_project_name) _main.
  • Click on the Sources tab in the new window. And then click the x next to the item at the top of the list.
  • Click on OK.
  • From the list of sources, right-click on D:usersprojplatform-authorizationsrcmain. Then, click OK to apply the changes.
  • Lastly, build your project and run.

Muhammad Zeeshan avatar
Muhammad Zeeshan avatar

I have been working as a Flutter app developer for a year now. Firebase and SQLite have been crucial in the development of my android apps. I have experience with C#, Windows Form Based C#, C, Java, PHP on WampServer, and HTML/CSS on MYSQL, and I have authored articles on their theory and issue solving. I’m a senior in an undergraduate program for a bachelor’s degree in Information Technology.

LinkedIn

Related Article — Java Error

  • Java.Lang.VerifyError: Bad Type on Operand Stack
  • Error Opening Registry Key ‘Software JavaSoft Java Runtime Environment.3’ in Java
  • Identifier Expected Error in Java
  • Error: Class, Interface, or Enum Expected in Java
  • Unreported Exception Must Be Caught or Declared to Be Thrown
  • Java.Lang.OutOfMemoryError: Unable to Create New Native ThreadEzoic
  • Понравилась статья? Поделить с друзьями:
  • Java lang classcastexception как исправить
  • Java jvm used by gradle ran out of available ram mcreator ошибка
  • Java jvm crash error 11
  • Java javascript error
  • Java io ioexception удаленный хост принудительно разорвал подключение как исправить