Ошибка: Exception in thread “main” java
Если вы сталкивались с ошибками Exception in thread “main”, то в этой статье я расскажу что это значит и как исправить ее на примерах.
При работе в среде Java, типа Eclipse или Netbeans, для запуска java-программы, пользователь может не столкнуться с этой проблемой, потому что в этих средах предусмотрен качественный запуск с правильным синтаксисом и правильной командой.
Здесь мы рассмотрим несколько общих java-исключений(Exceptions) в основных исключениях потоков, которые вы можете наблюдать при запуске java-программы с терминала.
Исключение в потоке java.lang.UnsupportedClassVersionError
Это исключение происходит, когда ваш класс java компилируется из другой версии JDK и вы пытаетесь запустить его из другой версии java. Рассмотрим это на простом примере:
Когда создаётся проект в Eclipse, он поддерживает версию JRE, как в Java 7, но установлен терминал Jawa 1.6. Из-за настройки Eclipse IDE JDK, созданный файл класса компилируется с Java 1.7.
Теперь при попытке запустить эту версию с терминала, программа выдает следующее сообщение исключения.
Если запустить версию Java1.7, то это исключение не появится. Смысл этого исключения – это невозможность компилирования java-файла с более свежей версии на устаревшей версии JRE.
Исключение java.lang.NoClassDefFoundError
Существует два варианта. Первый из них – когда программист предоставляет полное имя класса, помня, что при запуске Java программы, нужно просто дать имя класса, а не расширение.
Обратите внимание: если написать: .class в следующую команду для запуска программы – это вызовет ошибку NoClassDefFoundError. Причина этой ошибки — когда не удается найти файл класса для выполнения Java.
Второй тип исключения происходит, когда Класс не найден.
Обратите внимание, что класс ExceptionInMain находится в пакете com.journaldev.util, так что, когда Eclipse компилирует этот класс, он размещается внутри /com/journaldev/util. Следовательно: класс не найден. Появится сообщение об ошибке.
Исключение java.lang.NoSuchMethodError: main
Это исключение происходит, когда вы пытаетесь запустить класс, который не имеет метод main. В Java.7, чтобы сделать его более ясным, изменяется сообщение об ошибке:
Всякий раз, когда происходит исключение из метода main – программа выводит это исключение на консоль.
В первой части сообщения поясняется, что это исключение из метода main, вторая часть сообщения указывает имя класса и затем, после двоеточия, она выводит повторно сообщение об исключении.
Например, если изменить первоначальный класс появится сообщение System.out.println(10/0) ; Программа укажет на арифметическое исключение.
Методы устранения исключений в thread main
Выше приведены некоторые из распространенных исключений Java в потоке main, когда вы сталкиваетесь с одной из следующих проверок:
- Эта же версия JRE используется для компиляции и запуска Java-программы.
- Вы запускаете Java-класс из каталога классов, а пакет предоставляется как каталог.
- Ваш путь к классу Java установлен правильно, чтобы включить все классы зависимостей.
- Вы используете только имя файла без расширения .class при запуске.
- Синтаксис основного метода класса Java правильный.
Средняя оценка 2.2 / 5. Количество голосов: 10
Спасибо, помогите другим — напишите комментарий, добавьте информации к статье.
Или поделись статьей
Видим, что вы не нашли ответ на свой вопрос.
Помогите улучшить статью.
Напишите комментарий, что можно добавить к статье, какой информации не хватает.
How to fix «Exception in thread main» in java?
An exception is an issue (run time error) occurred during the execution of a program. When an exception occurred the program gets terminated abruptly and, the code past the line that generated the exception never gets executed.
Example
Output
Types of exceptions
In Java There are two types of exceptions
- Checked Exception − A checked exception is an exception that occurs at the time of compilation, these are also called as compile time exceptions. These exceptions cannot simply be ignored at the time of compilation; the programmer should take care of (handle) these exceptions.
- Unchecked Exception − An unchecked exception is the one which occurs at the time of execution. These are also called as Runtime Exceptions. These include programming bugs, such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation.
Exception in thread main
The display pattern of the runtime exception/unchecked exception is «Exception in thread main» i.e. whenever a runtime exception occurs the message starts with this line.
Example
In following Java program, we have an array with size 5 and we are trying to access the 6th element, this generates ArrayIndexOutOfBoundsException.
Run time exception
Example
In the following example we are trying to create an array by using a negative number for the size value, this generates a NegativeArraySizeException.
Run time exception
On executing, this program generates a run time exception as shown below.
Handling runtime exceptions
You can handle runtime exceptions and avoid abnormal termination but, there is no specific fix for runtime exceptions in Java, depending on the exception, type you need to change the code.
For example, if you need to fix the ArrayIndexOutOfBoundsException in the first program listed above you need to remove/change the line that accesses index positon of the array beyond its size.
Class Throwable
Instances of two subclasses, Error and Exception , are conventionally used to indicate that exceptional situations have occurred. Typically, these instances are freshly created in the context of the exceptional situation so as to include relevant information (such as stack trace data).
A throwable contains a snapshot of the execution stack of its thread at the time it was created. It can also contain a message string that gives more information about the error. Over time, a throwable can suppress other throwables from being propagated. Finally, the throwable can also contain a cause: another throwable that caused this throwable to be constructed. The recording of this causal information is referred to as the chained exception facility, as the cause can, itself, have a cause, and so on, leading to a «chain» of exceptions, each caused by another.
One reason that a throwable may have a cause is that the class that throws it is built atop a lower layered abstraction, and an operation on the upper layer fails due to a failure in the lower layer. It would be bad design to let the throwable thrown by the lower layer propagate outward, as it is generally unrelated to the abstraction provided by the upper layer. Further, doing so would tie the API of the upper layer to the details of its implementation, assuming the lower layer’s exception was a checked exception. Throwing a «wrapped exception» (i.e., an exception containing a cause) allows the upper layer to communicate the details of the failure to its caller without incurring either of these shortcomings. It preserves the flexibility to change the implementation of the upper layer without changing its API (in particular, the set of exceptions thrown by its methods).
A second reason that a throwable may have a cause is that the method that throws it must conform to a general-purpose interface that does not permit the method to throw the cause directly. For example, suppose a persistent collection conforms to the Collection interface, and that its persistence is implemented atop java.io . Suppose the internals of the add method can throw an IOException . The implementation can communicate the details of the IOException to its caller while conforming to the Collection interface by wrapping the IOException in an appropriate unchecked exception. (The specification for the persistent collection should indicate that it is capable of throwing such exceptions.)
A cause can be associated with a throwable in two ways: via a constructor that takes the cause as an argument, or via the initCause(Throwable) method. New throwable classes that wish to allow causes to be associated with them should provide constructors that take a cause and delegate (perhaps indirectly) to one of the Throwable constructors that takes a cause. Because the initCause method is public, it allows a cause to be associated with any throwable, even a «legacy throwable» whose implementation predates the addition of the exception chaining mechanism to Throwable .
By convention, class Throwable and its subclasses have two constructors, one that takes no arguments and one that takes a String argument that can be used to produce a detail message. Further, those subclasses that might likely have a cause associated with them should have two more constructors, one that takes a Throwable (the cause), and one that takes a String (the detail message) and a Throwable (the cause).
Lesson: Common Problems (and Their Solutions)
Compiler Problems
Common Error Messages on Microsoft Windows Systems
‘javac’ is not recognized as an internal or external command, operable program or batch file
If you receive this error, Windows cannot find the compiler ( javac ).
Here’s one way to tell Windows where to find javac . Suppose you installed the JDK in C:\jdk1.8.0 . At the prompt you would type the following command and press Enter:
If you choose this option, you’ll have to precede your javac and java commands with C:\jdk1.8.0\bin\ each time you compile or run a program. To avoid this extra typing, consult the section Updating the PATH variable in the JDK 8 installation instructions.
Class names, ‘HelloWorldApp’, are only accepted if annotation processing is explicitly requested
If you receive this error, you forgot to include the .java suffix when compiling the program. Remember, the command is javac HelloWorldApp.java not javac HelloWorldApp .
Common Error Messages on UNIX Systems
javac: Command not found
If you receive this error, UNIX cannot find the compiler, javac .
Here’s one way to tell UNIX where to find javac . Suppose you installed the JDK in /usr/local/jdk1.8.0 . At the prompt you would type the following command and press Return:
Note: If you choose this option, each time you compile or run a program, you’ll have to precede your javac and java commands with /usr/local/jdk1.8.0/ . To avoid this extra typing, you could add this information to your PATH variable. The steps for doing so will vary depending on which shell you are currently running.
Class names, ‘HelloWorldApp’, are only accepted if annotation processing is explicitly requested
If you receive this error, you forgot to include the .java suffix when compiling the program. Remember, the command is javac HelloWorldApp.java not javac HelloWorldApp .
Syntax Errors (All Platforms)
If you mistype part of a program, the compiler may issue a syntax error. The message usually displays the type of the error, the line number where the error was detected, the code on that line, and the position of the error within the code. Here’s an error caused by omitting a semicolon ( ; ) at the end of a statement:
If you see any compiler errors, then your program did not successfully compile, and the compiler did not create a .class file. Carefully verify the program, fix any errors that you detect, and try again.
Semantic Errors
In addition to verifying that your program is syntactically correct, the compiler checks for other basic correctness. For example, the compiler warns you each time you use a variable that has not been initialized:
Again, your program did not successfully compile, and the compiler did not create a .class file. Fix the error and try again.
Runtime Problems
Error Messages on Microsoft Windows Systems
Exception in thread «main» java.lang.NoClassDefFoundError: HelloWorldApp
If you receive this error, java cannot find your bytecode file, HelloWorldApp.class .
One of the places java tries to find your .class file is your current directory. So if your .class file is in C:\java , you should change your current directory to that. To change your directory, type the following command at the prompt and press Enter:
The prompt should change to C:\java> . If you enter dir at the prompt, you should see your .java and .class files. Now enter java HelloWorldApp again.
If you still have problems, you might have to change your CLASSPATH variable. To see if this is necessary, try clobbering the classpath with the following command.
Now enter java HelloWorldApp again. If the program works now, you’ll have to change your CLASSPATH variable. To set this variable, consult the Updating the PATH variable section in the JDK 8 installation instructions. The CLASSPATH variable is set in the same manner.
Could not find or load main class HelloWorldApp.class
A common mistake made by beginner programmers is to try and run the java launcher on the .class file that was created by the compiler. For example, you’ll get this error if you try to run your program with java HelloWorldApp.class instead of java HelloWorldApp . Remember, the argument is the name of the class that you want to use, not the filename.
Exception in thread «main» java.lang.NoSuchMethodError: main
The Java VM requires that the class you execute with it have a main method at which to begin execution of your application. A Closer Look at the «Hello World!» Application discusses the main method in detail.
Error Messages on UNIX Systems
Exception in thread «main» java.lang.NoClassDefFoundError: HelloWorldApp
If you receive this error, java cannot find your bytecode file, HelloWorldApp.class .
One of the places java tries to find your bytecode file is your current directory. So, for example, if your bytecode file is in /home/jdoe/java , you should change your current directory to that. To change your directory, type the following command at the prompt and press Return:
If you enter pwd at the prompt, you should see /home/jdoe/java . If you enter ls at the prompt, you should see your .java and .class files. Now enter java HelloWorldApp again.
If you still have problems, you might have to change your CLASSPATH environment variable. To see if this is necessary, try clobbering the classpath with the following command.
Now enter java HelloWorldApp again. If the program works now, you’ll have to change your CLASSPATH variable in the same manner as the PATH variable above.
Exception in thread «main» java.lang.NoClassDefFoundError: HelloWorldApp/class
A common mistake made by beginner programmers is to try and run the java launcher on the .class file that was created by the compiler. For example, you’ll get this error if you try to run your program with java HelloWorldApp.class instead of java HelloWorldApp . Remember, the argument is the name of the class that you want to use, not the filename.
Exception in thread «main» java.lang.NoSuchMethodError: main
The Java VM requires that the class you execute with it have a main method at which to begin execution of your application. A Closer Look at the «Hello World!» Application discusses the main method in detail.
Applet or Java Web Start Application Is Blocked
If you are running an application through a browser and get security warnings that say the application is blocked, check the following items:
Verify that the attributes in the JAR file manifest are set correctly for the environment in which the application is running. The Permissions attribute is required. In a NetBeans project, you can open the manifest file from the Files tab of the NetBeans IDE by expanding the project folder and double-clicking manifest.mf.
Verify that the application is signed by a valid certificate and that the certificate is located in the Signer CA keystore.
If you are running a local applet, set up a web server to use for testing. You can also add your application to the exception site list, which is managed in the Security tab of the Java Control Panel.