Как исправить ошибку exception in thread main

Если вы сталкивались с ошибками Exception in thread “main”, то в этой статье я расскажу что это значит и как исправить ее на примерах.

При работе в среде Java, типа Eclipse или Netbeans, для запуска java-программы, пользователь может не столкнуться с этой проблемой, потому что в этих средах предусмотрен качественный запуск с правильным синтаксисом и правильной командой.

Здесь мы рассмотрим несколько общих java-исключений(Exceptions) в основных исключениях потоков, которые вы можете наблюдать при запуске java-программы с терминала.

java.lang.UnsupportedClassVersionError ошибка в Java

Это исключение происходит, когда ваш класс java компилируется из другой версии JDK и вы пытаетесь запустить его из другой версии java. Рассмотрим это на простом примере:

package com.journaldev.util;

public class ExceptionInMain {

public static void main() {
System.out.println(10);
}

}

Когда создаётся проект в Eclipse, он поддерживает версию JRE, как в Java 7, но установлен терминал Jawa 1.6. Из-за настройки Eclipse IDE JDK, созданный файл класса компилируется с Java 1.7.

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

pankaj@Pankaj:~/Java7Features/bin$java com/journaldev/util/ExceptionInMain
Exception in thread "main" java.lang.UnsupportedClassVersionError: com/journaldev/util/ExceptionInMain : Unsupported major.minor version 51.0
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(ClassLoader.java:631)
at java.lang.ClassLoader.defineClass(ClassLoader.java:615)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)

Если запустить версию Java1.7, то это исключение не появится. Смысл этого исключения – это невозможность компилирования java-файла с более свежей версии на устаревшей версии JRE.

Исключение java.lang.NoClassDefFoundError

Существует два варианта. Первый из них – когда программист предоставляет полное имя класса, помня, что при запуске Java программы, нужно просто дать имя класса, а не расширение.

Обратите внимание: если написать: .class в следующую команду для запуска программы – это вызовет ошибку NoClassDefFoundError. Причина этой ошибки — когда не удается найти файл класса для выполнения Java.

pankaj@Pankaj:~/CODE/Java7Features/bin$java com/journaldev/util/ExceptionInMain.class

Exception in thread "main" java.lang.NoClassDefFoundError: com/journaldev/util/ExceptionInMain/class

Caused by: java.lang.ClassNotFoundException: com.journaldev.util.ExceptionInMain.class

at java.net.URLClassLoader$1.run(URLClassLoader.java:202)

at java.security.AccessController.doPrivileged(Native Method)

at java.net.URLClassLoader.findClass(URLClassLoader.java:190)

at java.lang.ClassLoader.loadClass(ClassLoader.java:306)

at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)

at java.lang.ClassLoader.loadClass(ClassLoader.java:247)

Второй тип исключения происходит, когда Класс не найден.

pankaj@Pankajs-MacBook-Pro:~/CODE/Java7Features/bin/com/journaldev/util$java ExceptionInMain

Exception in thread "main" java.lang.NoClassDefFoundError: ExceptionInMain (wrong name: com/journaldev/util/ExceptionInMain)

at java.lang.ClassLoader.defineClass1(Native Method)

at java.lang.ClassLoader.defineClass(ClassLoader.java:791)

at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)

at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)

at java.net.URLClassLoader.access$100(URLClassLoader.java:71)

at java.net.URLClassLoader$1.run(URLClassLoader.java:361)

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 sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:480)

Обратите внимание, что класс ExceptionInMain находится в пакете com.journaldev.util, так что, когда Eclipse компилирует этот класс, он размещается внутри /com/journaldev/util. Следовательно: класс не найден. Появится сообщение об ошибке.

Подробнее узнать об ошибке java.lang.NoClassDefFoundError.

Исключение java.lang.NoSuchMethodError: main

Это исключение происходит, когда вы пытаетесь запустить класс, который не имеет метод main. В Java.7, чтобы сделать его более ясным, изменяется сообщение об ошибке:

pankaj@Pankaj:~/CODE/Java7Features/bin$ java com/journaldev/util/ExceptionInMain

Error: Main method not found in class com.journaldev.util.ExceptionInMain, please define the main method as:

public static void main(String[] args)

Exception in thread "main" java.lang.ArithmeticException

Всякий раз, когда происходит исключение из метода main – программа выводит это исключение на консоль.

В первой части сообщения поясняется, что это исключение из метода main, вторая часть сообщения указывает имя класса и затем, после двоеточия, она выводит повторно сообщение об исключении.

Например, если изменить первоначальный класс появится сообщение System.out.println(10/0); Программа укажет на арифметическое исключение.

Exception in thread "main" java.lang.ArithmeticException: / by zero

at com.journaldev.util.ExceptionInMain.main(ExceptionInMain.java:6)

Методы устранения исключений в thread main

Выше приведены некоторые из распространенных исключений Java в потоке main, когда вы сталкиваетесь с одной из следующих проверок:

  1. Эта же версия JRE используется для компиляции и запуска Java-программы.
  2. Вы запускаете Java-класс из каталога классов, а пакет предоставляется как каталог.
  3. Ваш путь к классу Java установлен правильно, чтобы включить все классы зависимостей.
  4. Вы используете только имя файла без расширения .class при запуске.
  5. Синтаксис основного метода класса Java правильный.



I’ve just created a project on Eclipse and imported some source files (existing project). But I can’t compile it ! Ok, the project has got several source files, so I wanted to compile only the Main.java file (with eclipse not in the command line, in the command line it worked!) but all what I get is this error :

capture_eclipse

As you can see the Main.java file is straighforward, just a hello world !

What’s the matter ?

Thanks

asked Dec 13, 2009 at 17:35

Amokrane Chentir's user avatar

Amokrane ChentirAmokrane Chentir

29.8k37 gold badges114 silver badges158 bronze badges

2

«Unresolved compilation problem» means that the class hasn’t compiled successfully. Eclipse will still let you run code that doesn’t compile, but any of the specific bits which don’t compile will throw this error. Look in the «Problems» tab to see what’s wrong.

From the look of the Package Explorer view, every single class has a problem… perhaps the file location doesn’t match the package declaration? That would match the position of the pink box just to the right of the vertical scrollbar for the class — it suggests that the error is right at the top of the file, which is where the package declaration would be.

answered Dec 13, 2009 at 17:40

Jon Skeet's user avatar

Jon SkeetJon Skeet

1.4m861 gold badges9099 silver badges9172 bronze badges

3

You have a compilation error at the top of your Main.java file, just out of sight in the screenshot. Probably an unresolvable import or a wrong/missing package declaration.

answered Dec 13, 2009 at 17:43

Michael Borgwardt's user avatar

Michael BorgwardtMichael Borgwardt

341k78 gold badges481 silver badges719 bronze badges

1

It is simple in my case that the imported project needs 32 bit jre to run but cannot be compiled in the same. In IDE, if you click run, it will try to compile and run the project in single shot so fails due to 32 bit jre for compilation with the above reported error.
So i used 64 bit compiler and started to run and got compiled successfully but thrown error that needs 34 bit jre for some of the SWT used in the project. Again i changed the 32 bit jre and run the project, it is gone ! THE ERROR IS GONE NOW !

answered Mar 6, 2019 at 15:10

Vijayakanth G's user avatar

You can get the error «Exception in thread «main»
java.lang.Error: Unresolved compilation problem:» if your public class name differs from your file name.

example:

File Name:

ServiceRequest.java

Inside file, class is named differently; like

public class Service

answered May 9, 2019 at 20:32

Tom Stickel's user avatar

Tom StickelTom Stickel

19.5k6 gold badges111 silver badges113 bronze badges

How to fix unresolved compilation problemsThe exception in thread “main” java.lang.error: unresolved compilation problem: usually occurs due to syntax or typographical errors. Also, you might get the same exception due to using unknown or undefined classes and modules. Surprisingly, this article will let you know about all the possible causes in detail.

Read on to find out the most relevant cause and solve it at the earliest.

Contents

  • Why Does Exception in Thread “main” java.lang.error: Unresolved Compilation Problem: Occur?
    • – The Class or Module Is Not Imported
    • – Using Non-existent Classes
    • – A Syntax Error Resulting in Exception in Thread “main” java.lang.error: Unresolved Compilation Problem:
    • – A Typographical Error
  • How To Fix the Compilation Exception?
    • – Import the Necessary Classes and Modules
    • – Remove or Replace the Undefined Classes
    • – How To Resolve Java Lang Error in Eclipse?
    • – Use an Integrated Development Environment (IDE)
  • FAQ
    • – What Is Unresolved Compilation Problem Java?
    • – What Is Exception in Thread Main Java Lang Error?
  • Wrapping Up

The unresolved compilation problems occur because of syntax mistakes and typos. Moreover, using unknown or undefined classes and modules throw the same error. Please go through the causes described below to better understand the issues:

– The Class or Module Is Not Imported

If you use a class or module without importing the same in your program, then you’ll get the said java lang error. It indicates that you are instantiating a class or using a module that is unknown to the stated program.

– Using Non-existent Classes

If you use a class that isn’t already defined, then the same exception will pop up on your screen.

– A Syntax Error Resulting in Exception in Thread “main” java.lang.error: Unresolved Compilation Problem:

Even a common syntax error such as a missing or an extra curly bracket “{“ or a semicolon “;” can output the said exception. It includes sending the wrong arguments while calling the functions.

The below example code highlights the above-stated syntax errors:

public class myClass{
public static void main(String[] args){
anotherClass obj2 = new anotherClass();
obj2.myFunc(“Three”)
}
public class anotherClass{
public String myFunc(int num){
System.out.println(“You have entered:” + num);
}
}

– A Typographical Error

Another common cause behind the java lang error can be a typographical error. It usually happens when you code in hurry without realizing that you’ve typed the variable or function name incorrectly.

For example, you will get the above error if you have accidentally called the println() function as pirntln().

How To Fix the Compilation Exception?

Here are the easy-to-implement working solutions to lower your frustration level and resolve the said exception.

– Import the Necessary Classes and Modules

Look for the classes and modules used in your program. Next, import the given classes and modules. The stated simple step will kick away the exception if it is related to the classes and modules.

– Remove or Replace the Undefined Classes

You must remove the code that instantiates the undefined classes. Also, if you intended to call another class, then replacing the class name with a valid class name will work too.

– How To Resolve Java Lang Error in Eclipse?

You can notice the warnings shown in the Eclipse to identify the mistakes and correct them. Consequently, you will resolve the resulting java lang error.

– Use an Integrated Development Environment (IDE)

Using an IDE is the best possible solution to make the java lang error go away. It is because you’ll be notified regarding the typos and syntax errors. Moreover, you’ll be informed about the unknown modules and classes. You can then easily make the corrections and import the required classes or modules.

The above solution will let you skip the double-checking step before executing the code.

FAQ

The following questions might be disturbing you. So, here are the simplest answers to clear your confusion.

– What Is Unresolved Compilation Problem Java?

The above problem tells that there is a compilation error in the code. Although it is a generic error, you can learn more about it through the error description.

– What Is Exception in Thread Main Java Lang Error?

The stated exception tells that an error has occurred in the thread that is running the Java application. You can say that the given exception points towards the location of the error.

Wrapping Up

Now, it’s clear to you that the compilation error pops up due to common coding mistakes. Also, you get the said exception when the compiler isn’t aware of the classes and modules that are being used in your program. Plus, here is the list of fixing procedures obtained from the above article to make the long talk short:

  • You should import all the necessary classes and modules in your program
  • You should use only valid classes and modules
  • Using the IDE can help you in determining and correcting most of the coding mistakes that help in fixing the java lang error

Unresolved compilation problemsIndeed, the given exception seems to be complicated but it doesn’t demand anything else except for the careful investigation of the code.

  • Author
  • Recent Posts

Position is Everything

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

Many Java classes allow you to store objects in advanced ways. However, you may run into the Exception in Thread “Main” java.util.NoSuchElementException error when accessing them without care.

Keep reading to find out why the error happens and how you can prevent it.

Reproduce The Error

The java.util.NoSuchElementException error happens a lot when collections are used in Java. In particular, these two examples show how you may run into it when using StringTokenizer and Vector objects.

Example 1

import java.util.StringTokenizer;
public class NoSuchElementException {
    public static void example1() {
        String str = "Welcome to our website";
        StringTokenizer tokens = new StringTokenizer(str, " ");
        
        for(int i = 1; i < 6; ++i) {
            System.out.println(tokens.nextToken());
        }
    }
    public static void main(String[] args) {
        example1();
    }
}

In this example, we use the StringTokenizer class to split a string into tokens – one of the most popular applications of this class. However, after successfully printing out all the substrings, Java displays the error message related to java.util.NoSuchElementException.

Output

Welcome
to
our
website
Exception in thread "main" java.util.NoSuchElementException
	at java.base/java.util.StringTokenizer.nextToken(StringTokenizer.java:349)
	at NoSuchElementException.example1(NoSuchElementException.java:8)
	at NoSuchElementException.main(NoSuchElementException.java:12)

In this example, we use Vector and Enumeration to access elements of a vector in Java.

Example 2

import java.util.Vector;
import java.util.Enumeration;
public class NoSuchElementException {
    public static void example2() {
        Vector<String> str = new Vector<>();
        str.add("Welcome");
        str.add("to");
        str.add("our");
        str.add("website");
        Enumeration<String> e = str.elements();
        for(int i = 1; i < 6; ++i) {
            System.out.println(e.nextElement());
        }
    }
    public static void main(String[] args) {
        example2();
    }
}

As with the first example, this program also shows the java.util.NoSuchElementException error message after printing every element of our vector.

Output

Welcome
to
our
website
Exception in thread "main" java.util.NoSuchElementException: Vector Enumeration
	at java.base/java.util.Vector$1.nextElement(Vector.java:344)
	at NoSuchElementException.example2(NoSuchElementException.java:27)
	at NoSuchElementException.main(NoSuchElementException.java:32)

java.util.NoSuchElementException

NoSuchElementException is a subclass of RuntimeException. Many accessor methods throw this exception when they want to tell you that the element you request doesn’t exist.

Common methods that produce this error are StringTokenizer.nextToken(), Enumeration.nextElement(), and Iterator.next().

In the first example, we use a for loop to control how many times the program should invoke the StringTokenizer.nextToken().

Particularly, the loop calls it five times, while the StringTokenizer instance only has four elements. That is why for the fifth time, Java prints out NoSuchElementException since there are no more elements for the StringTokenizer.nextToken() method to access.

The same thing happens to the second example with the Enumeration interface. Our string provides it with only four elements, but the for loop also calls the nextElement() five times. As a result, we also get the NoSuchElementException error.

This is a runtime exception, meaning the compiler won’t be able to detect any problems with your code. It is not until you run it with the Java Virtual Machine, that this exception will display.

Keep in mind that, like other exceptions in the superclass RuntimeException, there is no need to declare NoSuchElementException in your constructor or method’s throws clause. That is why these exceptions are called ‘unchecked’.

How To Fix The Error

Instead of using the for loop, you can use StringTokenizer.hasMoreTokens() and Enumeration.hasMoreElements() methods.

Example 1

while (tokens.hasMoreTokens()) {
    System.out.println(tokens.nextToken());
}

Example 2

for (Enumeration<String> e = str.elements(); e.hasMoreElements();)
    System.out.println(e.nextElement());

These methods check whether the StringTokenizer and Enumeration have more elements that you can access.

Summary

The Exception in Thread “Main” java.util.NoSuchElementException error occurs when you access elements that don’t exist. You should perform a check to avoid this problem.

Maybe you are interested:

  • ERROR : ‘compileJava’ task (current target is 11) and ‘compileKotlin’ task (current target is 1.8) jvm target compatibility should be set to the same Java version in Java
  • java.lang.IllegalAccessError: class lombok.javac.apt.LombokProcessor cannot access class com.sun.tools.javac.processing.JavacProcessingEnvironment
  • Error: Non-static Variable/Method ‘#’ Cannot be Referenced from a Static Context

Robert J. Charles

My name is Robert. I have a degree in information technology and two years of expertise in software development. I’ve come to offer my understanding on programming languages. I hope you find my articles interesting.


Job: Developer
Name of the university: HUST
Major: IT
Programming Languages: Java, C#, C, Javascript, R, Typescript, ReactJs, Laravel, SQL, Python

Текст ошибки:

Exception in thread "main" java.lang.NullPointerException
    at TakeTheToken.main(TakeTheToken.java:26)

Пишу парсер кода с++, который разбивает всё на лексемы, но чёрт, не могу записать информацию в объект, что делать?

26 строка:
System.out.print(elements[0].token_type);

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class TakeTheToken {
 
    public String token;
    public String token_type;
 
 
    public TakeTheToken(String token, String token_type) {
        this.token = token;
        this.token_type = token_type;       
    }
 
    public static TakeTheToken [] elements;
 
    public static void main(String[] args) throws IOException {
        String str = Open();
        System.out.println(str);
        addToken(str);  
        System.out.print(elements[0].token_type);
    }
 
    public static String Open() throws IOException {
        File f = new File("D:\1.txt");
        FileReader fr = null;
        try {
            fr = new FileReader(f);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        @SuppressWarnings("resource")
        BufferedReader br = new BufferedReader(fr);
        StringBuffer sb = new StringBuffer();
        String eachLine = null;
        try {
            eachLine = br.readLine();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        while (eachLine != null) {
            sb.append(eachLine);
            sb.append("n");
            try {
                eachLine = br.readLine();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
 
 
 
        return sb.toString().replaceAll("[\n]", "");
 
    }
 
 
    public static void addToken(String str) { 
        char[] type = str.toCharArray();
        int i = 0;
        String word = "", number = "", charius = "";
        while (i < str.length()) {
            String typeChar = Character.toString(type[i]);
            if (RegExp(typeChar) == 1) {//Если буквы        
 
                while (RegExp(typeChar) == 1) {                 
                    word += typeChar;                   
                    i++;
                    if (i < str.length()) {
                        typeChar = String.valueOf(type[i]);
                    } else break;               
                }
                
                typeString(word, 1);
                System.out.print(word);
                word = "";
 
            } 
 
            if (RegExp(typeChar) == 2) {//Если цифры
                while (RegExp(typeChar) == 2) {                 
                    number += typeChar;                 
                    i++;
                    if (i < str.length()) {
                        typeChar = String.valueOf(type[i]);
                    } else break;
                }
 
 
                System.out.print(number);
                number = "";
 
            } 
 
            if (RegExp(typeChar) == 3) { 
                while (type[i] != ' ' && RegExp(typeChar) == 3) {                   
                    charius += typeChar;
                    if (i+1 < str.length()) {
                        typeChar = String.valueOf(type[i+1]);
                    } else break;
                    if (RegExp(typeChar) == 3) {
                        i++;
                        if (i < str.length()) {
                            typeChar = String.valueOf(type[i]);
                        }
                    }
                }
 
 
                System.out.print(charius);
                charius = "";
            }
 
            i++;
        }   
 
 
    }
 
    public int c = 0;
 
    public static void typeString(String str, int type) {       
        elements = new TakeTheToken[24];
        if (type == 1) {
            String[] s = {"int", "double", "float", "if", "else", "while", "for" };
            for (int i = 0; i < s.length; i++) {
                if (str.equals(s[i])) {                 
                    elements[i] = new TakeTheToken(str, "keywords");
                    i++;
                }
            }
        }
    }
 
 
    public static int RegExp(String str) {
        Pattern p = Pattern.compile("[a-zA-Z]");
        Matcher m = p.matcher(str);
 
        if (m.matches()) {
            return 1;
        }
 
 
        p = Pattern.compile("[0-9]");
        m = p.matcher(str);
 
        if (m.matches()) {
            return 2;
        } else return 3;
 
    }
 
}

Дебажил, элементы заносит верно, но когда доходит до 26 строки рушится и выдаёт ошибку.
Может объект криво создаю или заполняю?

Понравилась статья? Поделить с друзьями:
  • Как исправить ошибку error report
  • Как исправить ошибку error launching installer
  • Как исправить ошибку kernel data inpage error
  • Как исправить ошибку javascript
  • Как исправить ошибку java virtual machine launcher