Exception in thread main java lang nosuchmethoderror main

Ошибка: Exception in thread “main” java

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

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

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

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

Исключение в потоке java.lang.UnsupportedClassVersionError

Это исключение происходит, когда ваш класс 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.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 правильный.

Средняя оценка 2.1 / 5. Количество голосов: 16

Спасибо, помогите другим — напишите комментарий, добавьте информации к статье.

Видим, что вы не нашли ответ на свой вопрос.

Напишите комментарий, что можно добавить к статье, какой информации не хватает.

Источник

Exception in thread «main» java.lang.NoSuchMethodError: main [duplicate]

The class containing the main() function must be public, and you may only define one public class per file. You’ll want to have two separate files Risk.java and Territory.java .

EDIT: It turns out this isn’t true — I was able to run your initial code with the following command line:

But my earlier comments point to the best practice for a real app, such as a Risk game.

What class are you trying to run? If you’re using the class territory , that will work. Risk has no main method, though.

Can you figure out why this example causes the same issue?

Answer: because main() should be public static void!

Читайте также:  METANIT.COM

Could it just be a spacing issue? Your original post shows no space between the ‘]’ and ‘arg’.

public static void main (String[] arg) 

or, if that still doesn’t work:

public static void main (String arg[]) 

-1 No, both of those are immaterial considerations. (Normally I don’t downvote posts, but ones that suggest that formatting changes will make any difference demonstrate a deep misunderstanding of the language.)

@Adrian: Sometimes, yes. ( class Foo is different from classFoo .) Other times, such as here, no. Knowing when it makes a difference is a sign of a competent programmer.

People don’t need to make excuses for down-voting a blatantly wrong answer. Down-voting incorrect answers encourages people to verify their facts before posting.

@elduff: It’s one thing to say formatting is good for readability. It’s another to say it changes language semantics. (In a language like Python, formatting does indeed change semantics, but we’re talking about Java here.) Being a good programmer means you’re able to tell which is which.

@Adrian: Depends on how you define «deep misunderstanding». To me, if one doesn’t understand how code is tokenised in a given language (i.e., in Java, String[]args is tokenised the same as String [ ] args ), that says something about how much they understand the language.

Источник

How to fix java.lang.NoSuchMethodError: main Exception in thread «main» in Java? Example

java.lang.NoSucMethodError comes when Java code tries to call a method that does not exist on a class, this could be either static or non-static method. a most common manifestation of java.lang.NoSuchMethodError is running a class that doesn’t have the main method in Java. In this article, we will see what is » java.lang.NoSuchMethodError: main Exception in thread «main «», Why does java.lang.NoSuchMethodError comes and how to solve java.lang.NoSuchMethodError in Java.

What is «java.lang.NoSuchMethodError: main Exception in thread «main»»

java.lang.NoSuchMethodError: main Exception in thread

This is a manifestation of NoSuchMethodError in Java and complaining about «main» which is the name of method JVM tries to call but doesn’t find in offending class. «java.lang.NoSuchMethodError: main Exception in thread «main» can come due to various reasons like:

2) The signature of the main method is not correct. See here for all possible signatures of the main method in Java.

Example of «java.lang.NoSuchMethodError: main Exception in thread «main»

To better understand NoSuchMethodError in Java let’s see some common examples of java.lang.NoSuchMethodError and find out how and when they come:

There are very few scenarios on which java.lang.NoSuchMethodError comes during runtime because the compiler is able to check this error and flag it if doesn’t found the proper method except main which is an optional method and only checked by JVM during runtime.

Читайте также:  What is factory pattern in php

As I said earlier Another possible cause of «java.lang.NoSuchMethodError: main Exception in thread «main» is that you have the main method in class but the signature of the main method is not correct. to test this scenario let’s

public class Loan <
public String getPersonalLoan () <
return «Personal Loan» ;
> ;

public static void main ( String args ) <
System . out . println ( «Inside main in Java» ) ;
>
>

because in the main method args should be a string array and we have not added [] there and that’s why this error.

That’s all on How to fix java.lang.NoSuchMethodError: main Exception in thread «main. Ideally java.lang.NoSuchMethodError comes when we call a method that doesn’t exist in class but mostly typo, incorrect argument or incorrect signature turns out to be the real culprit.

5 comments :

I didn’t understand point that why would someone want to execute a class without main ? Though error is quite clear «java.lang.NoSuchMethodError: main Exception in thread «main» , first part says that there is no main method in this class «java.lang.NoSuchMethodError: main» and second part says that Exception is occurred in main thread.

class Dogint size;
String name;
void bark()
if(size>70)
>
else if(size>14)
System.out.println(«foo foo»);
>
else
System.out.println(«yip yip»);
>
>
>
class Dogtestdrivepublic static void main(String[] args)
Dog one = new Dog();
one.size=80;
Dog two = new Dog();
two.size=20;
Dog three = new Dog();
three.size=12;
one.bark();
two.bark();
three.bark();
>
>
i get the same error. can anyone tell me where is the error?

the following is my code and i am getting same error can you please correct it??

import java.lang.*;
import java.util.*;

class Core implements RunnableString name;
Thread t;
Core(String n)name=n;
t=new Thread(this ,n);
System.out.print(«thread name»+t);
t.start();
>
public void run()tryfor(int i=0;i<5;i++)System.out.print(name+" : "+i);
Thread.sleep(1000);>
>catch(InterruptedException e)
>
System.out.print(» main thread exiting «);
>
>

class Series public static void main(String arun[])new Core(«one»);
new Core(«two»);
new Core(«three»);
tryThread.sleep(1000);
>catch(InterruptedException e)
System.out.print(«main thread interrrupted»+e);
>
>
>

make two files one with class Dog, the other file with the other class.

This is my program which is generating the same erroe
Please help me to find out the error

import java.io.*;
class A
public static void main(String args[])throws IOException
int i;
FileInputStream fin=null;
FileOutputStream fout=null;
try
fin=new FileInputStream (args[0]);
>
catch(FileNotFoundException temp)
System.out.println(«Exception caught»+temp);
>

try
fout=new FileOutputStream (args[1]);
>
catch(FileNotFoundException temp)
System.out.println(«Exception caught»+temp);
>
catch(ArrayIndexOutOfBoundsException ai)

Источник

Оцените статью