Ошибка exception in thread main java lang unsupportedclassversionerror

This was a fresh linux Mint xfce machine

I have been battling this for a about a week. I’m trying to learn Java on Netbeans IDE and so naturally I get the combo file straight from Oracle. Which is a package of the JDK and the Netbeans IDE together in a tar file located here.

located
http://www.oracle.com/technetwork/java/javase/downloads/index.html
file name
JDK 8u25 with NetBeans 8.0.1

after installing them (or so I thought) I would make/compile a simple program like «hello world» and that would spit out a jar file that you would be able to run in a terminal. Keep in mind that the program ran in the Netbeans IDE.

I would end up with this error: java.lang.UnsupportedClassVersionError:

Even though I ran the file from oracle website I still had the old version of the Java runtime which was not compatible to run my jar file which was compiled with the new java runtime.

After messing with stuff that was mostly over my head from setting Paths to editing .bashrc with no remedy.

I came across a solution that was easy enough for even me. I have come across something that auto installs java and configures it on your system and it works with the latest 1.8.*

One of the steps is adding a PPA wasn’t sure about this at first but seems ok as it has worked for me


sudo add-apt-repository ppa:webupd8team/java

sudo apt-get update

sudo apt-get install oracle-java8-installer


domenic@domenic-AO532h ~ $ java -version
java version «1.8.0_25»
Java(TM) SE Runtime Environment (build 1.8.0_25-b17)
Java HotSpot(TM) Server VM (build 25.25-b02, mixed mode)

I think it also configures the browser java as well.

I hope this helps others.

Если вы сталкивались с ошибками 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 правильный.



This was a fresh linux Mint xfce machine

I have been battling this for a about a week. I’m trying to learn Java on Netbeans IDE and so naturally I get the combo file straight from Oracle. Which is a package of the JDK and the Netbeans IDE together in a tar file located here.

located
http://www.oracle.com/technetwork/java/javase/downloads/index.html
file name
JDK 8u25 with NetBeans 8.0.1

after installing them (or so I thought) I would make/compile a simple program like «hello world» and that would spit out a jar file that you would be able to run in a terminal. Keep in mind that the program ran in the Netbeans IDE.

I would end up with this error: java.lang.UnsupportedClassVersionError:

Even though I ran the file from oracle website I still had the old version of the Java runtime which was not compatible to run my jar file which was compiled with the new java runtime.

After messing with stuff that was mostly over my head from setting Paths to editing .bashrc with no remedy.

I came across a solution that was easy enough for even me. I have come across something that auto installs java and configures it on your system and it works with the latest 1.8.*

One of the steps is adding a PPA wasn’t sure about this at first but seems ok as it has worked for me


sudo add-apt-repository ppa:webupd8team/java

sudo apt-get update

sudo apt-get install oracle-java8-installer


domenic@domenic-AO532h ~ $ java -version
java version «1.8.0_25»
Java(TM) SE Runtime Environment (build 1.8.0_25-b17)
Java HotSpot(TM) Server VM (build 25.25-b02, mixed mode)

I think it also configures the browser java as well.

I hope this helps others.

The java.lang.UnsupportedClassVersionError is a runtime error in Java that occurs when a Java Virtual Machine (JVM) encounters a class file with a version that is not supported by the JVM. This error typically arises when there is a mismatch between the version of the JVM executing the code and the version in which the class file was compiled.

When the JVM encounters this error, it signifies that the class file was compiled with a higher version of Java than the one running the JVM. This mismatch can prevent the execution of the program, as the JVM may not understand or support certain bytecode features introduced in higher versions of Java.

The objective of this tutorial is to guide you through the resolution of the java.lang.UnsupportedClassVersionError. We will explore common scenarios that lead to this error and provide practical solutions to overcome it. By the end of this tutorial, you will have a solid understanding of how to identify and resolve this error, ensuring compatibility between the Java versions used for compilation and execution.

Understanding the Error

Definition of the java.lang.UnsupportedClassVersionError and its Common Causes

The java.lang.UnsupportedClassVersionError is a runtime error that occurs when a Java Virtual Machine (JVM) encounters a class file with a version number that is not supported by the JVM. This error typically arises due to a mismatch between the Java version used to compile the class and the Java version used to execute it.

The most common causes of UnsupportedClassVersionError include:

  1. Java Version Mismatch: This occurs when a class file is compiled with a higher version of Java than the version used to run it. For example, if a class is compiled with Java 11 but executed with Java 8, the JVM will throw an UnsupportedClassVersionError.
  2. Outdated JRE: If an older version of the Java Runtime Environment (JRE) is used to execute a class file compiled with a newer Java version, the UnsupportedClassVersionError can occur.

The Relationship between Java Versions and Class Versions

Understanding the relationship between Java versions and class versions is essential to grasp the nature of the UnsupportedClassVersionError error. In Java, each version release introduces new features, enhancements, and changes to the language and its runtime environment. When a class file is compiled, it is associated with a specific class version that corresponds to the Java version used during compilation.

The class version number is stored in the class file’s bytecode and indicates the Java version compatibility of the class. The JVM checks this class version when loading the class to ensure compatibility between the class file and the JVM’s version.

For example, consider a class file compiled with Java 11. It will have a class version of 55 (Java 11’s major version number). When this class is executed, the JVM checks if the class version matches the JVM’s supported version. If the JVM is an older version that supports Java 8, which has a class version of 52, the JVM will throw an UnsupportedClassVersionError.

It’s important to note that JVMs are generally backward compatible, meaning they can run class files compiled with older versions of Java. However, running class files compiled with a higher Java version on an older JVM can result in the UnsupportedClassVersionError.

Here’s an example code snippet that demonstrates the UnsupportedClassVersionError in action:

// Sample.java (compiled with Java 11)
public class Sample {
    public static void main(String[] args) {
        System.out.println("Hello, Java!");
    }
}

If the above Sample.class file compiled with Java 11 is executed with Java 8, the following error would occur:

Exception in thread "main" java.lang.UnsupportedClassVersionError: Sample has been compiled by a more recent version of the Java Runtime (class file version 55.0), this version of the Java Runtime only recognizes class file versions up to 52.0

This error message indicates that the class file was compiled with a higher Java version (55.0) than the one supported by the JVM (up to 52.0).

Understanding the causes and the relationship between Java versions and class versions is crucial for effectively resolving the java.lang.UnsupportedClassVersionError and ensuring compatibility between the compiled class and the executing JVM.

Common Scenarios and Solutions

Running a Java Class Compiled with a Higher Version

When encountering the java.lang.UnsupportedClassVersionError while running a Java class, it typically indicates that the class was compiled with a higher version of Java than the one being used for execution. This error commonly occurs when attempting to run a class compiled with a newer Java version on an older Java Runtime Environment (JRE). The error message may resemble the following:

Exception in thread "main" java.lang.UnsupportedClassVersionError: MyClass has been compiled by a more recent version of the Java Runtime (class file version X.X), this version of the Java Runtime only recognizes class file versions up to X.X

Solution

To resolve this issue, you need to identify the Java version of the compiled class and then choose an appropriate solution.

One way to determine the Java version of the compiled class is by using the javap command-line tool. Open your command prompt or terminal and navigate to the directory containing the class file. Then, run the following command:

javap -verbose MyClass

Replace MyClass with the name of your class. Look for the major version in the output, which indicates the Java version used for compilation.

If the class is compiled with a higher Java version than the JRE, you have a couple of solutions, first try to update your JRE to a version that is equal to or greater than the Java version used for compilation. Visit the official Java website to download and install the latest JRE.

If updating the JRE is not feasible or desirable, you can recompile the class with a compatible Java version. This involves modifying the source code and compiling it using a compatible JDK. Ensure that the JDK version matches the target JRE version to avoid compatibility issues.

Here’s an example of compiling a class with a specific target Java version using the -target flag:

javac -target X.X -source X.X MyClass.java

Replace X.X with the desired Java version (e.g., 1.8, 11, 17) that matches your target execution environment.

Executing a Java Application on an Older JRE

If you encounter the java.lang.UnsupportedClassVersionError while executing a Java application, it indicates that the JRE being used is older than the Java version in which the application was compiled. This situation can arise when trying to run an application compiled with a newer Java version on an older JRE. The error message may resemble the following:

Exception in thread "main" java.lang.UnsupportedClassVersionError: MyClass has been compiled by a more recent version of the Java Runtime (class file version X.X), this version of the Java Runtime only recognizes class file versions up to X.X

The error message suggests that the class was compiled with a higher Java version than the current JRE supports. This mismatch between the compiled class and the JRE version can prevent the application from running correctly.

Solution

To determine the JRE version you have installed, open a command prompt or terminal and execute the following command:

java -version

This command will display the installed JRE version. Ensure that the installed JRE version is compatible with the Java version in which the application was compiled.

If the JRE version is older than the compiled class version, you have a couple of options, visit the official Java website and download the latest version of the JRE compatible with the class file’s Java version. Install the updated JRE and ensure that the application runs using the newer version.

Alternatively, you can create an executable JAR file that includes the necessary JRE version. This ensures that the application runs with the required Java version regardless of the installed JRE. Tools like Apache Maven or Gradle can help you build an executable JAR file with embedded dependencies.

Using a Different JDK and JRE Version

The java.lang.UnsupportedClassVersionError can also occur when there is a mismatch between the Java Development Kit (JDK) used for compilation and the Java Runtime Environment (JRE) used for execution. This discrepancy can arise when different versions of the JDK and JRE are utilized.

The JDK is responsible for compiling Java source code into bytecode, whereas the JRE is responsible for executing the bytecode on the target system. If the compiled class is not compatible with the JRE version due to a mismatch between the JDK and JRE versions, the java.lang.UnsupportedClassVersionError can occur.

Solution

Ensure that the JDK and JRE versions are aligned by following these steps:

Open a command prompt or terminal and execute the following command:

javac -version

This command will display the version of the installed JDK, make note of this version. Then execute the following command:

java -version

This command will display the version of the installed JRE. Ensure that the JRE version matches or is compatible with the JDK version used for compilation.

If the JRE version is newer than the JDK version used for compilation, you should update the JDK to a compatible version. Visit the official Java website to download and install the latest JDK.

If the JDK version is newer than the JRE version, update the JRE to a version that matches or is compatible with the JDK version. Download the appropriate JRE from the official Java website and install it on your system.

Ensure that both the JDK and JRE versions are aligned to avoid the java.lang.UnsupportedClassVersionError when executing the compiled Java classes.

Best Practices and Tips

Maintaining Consistency between JDK, JRE, and Java Class Versions

When working with Java applications, it’s crucial to maintain consistency between the Java Development Kit (JDK), Java Runtime Environment (JRE), and the version of Java used to compile your classes. Inconsistencies can lead to the java.lang.UnsupportedClassVersionError and other compatibility issues. Here are some best practices to follow:

  1. JDK Version: Ensure that the JDK version you use for compilation matches or is compatible with the JRE version where you intend to execute the Java classes. To check your JDK version, open a command prompt or terminal and enter the following command:
    javac -version
  2. JRE Version: Verify that the JRE version you have installed matches the desired runtime environment. You can check the JRE version by running the following command:
    java -version
    
  3. Target Java Version: When compiling your Java classes, it’s important to specify the target Java version explicitly. This ensures compatibility with the JRE where the classes will be executed. To specify the target Java version during compilation, use the -target flag followed by the desired version number. For example:
    javac -target 1.8 MyClass.java
    

    This command instructs the compiler to generate bytecode compatible with Java 8. By specifying the target version, you can ensure that the compiled classes are compatible with the desired JRE.

Importance of Version Management and Compatibility Checks

Version management and compatibility checks play a vital role in preventing the java.lang.UnsupportedClassVersionError and ensuring smooth execution of Java applications. Here’s why they are important:

  1. Cross-Version Compatibility: Different versions of Java may introduce new language features, APIs, or changes in bytecode. Ensuring compatibility between different versions avoids potential runtime errors.
  2. Deployment Environment: It’s essential to know the version of JRE available in the deployment environment. This knowledge enables you to compile classes using the corresponding JDK and set the appropriate target version.
  3. Compatibility Testing: Before deploying an application, perform thorough compatibility testing to ensure that it functions correctly across different Java versions and environments.

Automating Version Checks with Build Tools or IDE Features

To simplify version management and compatibility checks, consider leveraging build tools or IDE features that automate these processes. Here are some options:

  1. Build Tools: Popular build tools like Apache Maven, Gradle, or Ant provide mechanisms to specify the JDK and JRE versions, manage dependencies, and enforce compilation compatibility. These tools can automatically verify the target version and handle the required configurations.
  2. IDE Features: Integrated Development Environments such as Eclipse, IntelliJ IDEA, and NetBeans offer built-in features to manage Java versions and perform compatibility checks. These IDEs can highlight potential version conflicts, assist in setting the target Java version, and provide quick fixes to resolve compatibility issues.

In conclusion, maintaining consistency between JDK, JRE, and Java class versions is crucial for avoiding java.lang.UnsupportedClassVersionError and ensuring smooth execution of Java applications. By following best practices, conducting compatibility checks, and automating version management, developers can mitigate compatibility issues and deliver robust and compatible Java applications.

Conclusion

In this tutorial, we explored the java.lang.UnsupportedClassVersionError and learned how to resolve it effectively. We discovered that this error occurs due to compatibility issues between the Java version used for compilation and the Java Runtime Environment (JRE) version used for execution.

Now armed with the knowledge and solutions provided in this tutorial, you are well-equipped to tackle the java.lang.UnsupportedClassVersionError and optimize your Java development experience. Don’t forget to explore the Troubleshooting Java Applications page, where you can find a wide range of tutorials that specifically tackle different Java errors. Keep coding and happy troubleshooting!

Frequently asked questions

  • What if I have multiple versions of the JDK installed on my system? How can I ensure compatibility?
    In case you have multiple JDK versions installed, you can use build tools like Maven or Gradle to specify the desired JDK version in your project configuration. These build tools help manage dependencies and ensure compatibility.
  • Can the java.lang.UnsupportedClassVersionError occur in a web application deployed on a server?
    Yes, the java.lang.UnsupportedClassVersionError can occur in a web application if there is a mismatch between the Java version used for compilation and the JRE version installed on the server. Ensure that the server’s JRE version is compatible with the compiled classes.
  • Is it possible to encounter the java.lang.UnsupportedClassVersionError when using an Integrated Development Environment (IDE) such as Eclipse or IntelliJ?
    Yes, it is possible to encounter this error in an IDE if there is a discrepancy between the JDK used by the IDE for compilation and the JRE used for running the application. Verify and align the JDK and JRE versions within your IDE to resolve this issue.
  • Are there any tools or plugins available to automate the detection of Java version compatibility issues?
    Yes, there are tools and plugins available, such as the Eclipse Compiler for Java (ECJ) or the Animal Sniffer Maven Plugin, which can help detect Java version compatibility issues during the build process and provide warnings or errors accordingly.

Introduction: Early-Stage Runtime Errors

Runtime errors occur when a program is being executed and, in the case of compiled languages, after the program has been successfully compiled. Runtime errors are, therefore, harder to detect and prevent than compile-time errors [1]. In Java, some of these runtime errors (namely throwable objects which are not exceptions) are triggered at a very early stage, while the program is basically starting up. Namely, there is a process of dynamic loading, linking, and initializing of classes and interfaces by the Java Virtual Machine (JVM) that occurs at the very beginning of execution of any Java application [2]. This allows for a certain category of errors to be captured and dealt with before the program effectively starts.

This category of high level runtime errors in Java is represented by classes which are direct descendants of the java.lang.Error class [3], including the java.lang.LinkageError class which denotes errors occurring during the aforementioned startup process [4]. An instance of the Error class (or any of its subclasses) is a throwable object that a program is not expected or advised to handle, but instead, should cause immediate termination of the program. This is because most of these errors occur as a result of abnormal conditions, often so severe that it is impossible to know or control what further execution of the program might do. LinkageError instances in particular indicate critical class-related errors triggered during the class linking phase of the startup process, usually as a consequence of some post-compilation changes in the bytecode or the Java environment.

What is the UnsupportedClassVersionError Error and Why Does it Happen?

The java.lang.UnsupportedClassVersionError class extends java.lang.ClassFormatError which is thrown whenever the JVM attempts to read a class file and determines that the file is malformed or otherwise cannot be interpreted as a class file [5][6]. As per Java’s error class hierarchy (Figure 1), an instance of UnsupportedClassVersionError is also a LinkageError which means that the error is identified during the JVM class linking process.

UnsupportedClassVersionError class hierarchy

Figure 1. UnsupportedClassVersionError class hierarchy

The specific issue that the UnsupportedClassVersionError error raises is the detection of a class file which had been compiled with a newer version of Java than the one used to run it. For instance, if a specific .class file has been compiled with Java Development Kit (JDK) 15, trying to run it with Java Runtime Environment (JRE) 8 will trigger the UnsupportedClassVersionError error. This almost invariably happens when someone attempts to run a program with a JDK or a JRE version that is incompatible with, i.e., lower than the Java version in which the code was compiled.

How to Fix the UnsupportedClassVersionError Error

The solution to the UnsupportedClassVersionError error generally boils down to two options:

  • Run the code with a newer version of Java/JRE, or
  • Recompile the code with an older Java/JDK compiler.

As a variant of #2, recompiling the code can also be done by specifying the “target” or “release” parameter of a newer Java/JDK compiler to an earlier version of Java, to produce backward-compatible bytecode.

Before recompiling any code, it is important to know the runtime version of both the already compiled code and the environment in which it needs to run on. The message accompanying the UnsupportedClassVersionError error provides this information in the form of class file versions, which can be mapped directly to a specific Java version, using the values from the table below.

Table 1. Class file format major versions
Java SE (JDK) Major Version Release Date
17 61 September 2021
16 60 March 2021
15 59 September 2020
14 58 March 2020
13 57 September 2019
12 56 March 2019
11 55 September 2018
10 54 March 2018
9 53 September 2017
8 52 March 2014
7 51 July 2011
6 50 December 2006
5.0 49 September 2004
1.4 48 February 2002
1.3 47 May 2000
1.2 46 December 1998
1.1 45 February 1997
1.01 45 May 1996

UnsupportedClassVersionError Error Example

Below is an example of the UnsupportedClassVersionError error, indicating that the class com.rollbar.ExampleApp was compiled with Java 17 (class file version 61) but executed with Java 8 (class file version 52).

Exception in thread "main" java.lang.UnsupportedClassVersionError: com/rollbar/ExampleApp 
  has been compiled by a more recent version of the Java Runtime (class file version 61.0), 
  this version of the Java Runtime only recognizes class file versions up to 52.0
Figure 2: UnsupportedClassVersionError example

Using a newer Java version

The most straightforward solution is to update the JRE on the machine on which the code is running. Executing the commands echo %JAVA_HOME% and java -version inside a terminal should point to the existing Java installation directory and its version number. This can be particularly useful to pinpoint which version is in use when multiple JREs are installed on the same machine. From there, downloading and updating the JAVA_HOME variable to point to the newer Java version (e.g. Java 17) [7] will fix the UnsupportedClassVersionError error.

Recompiling by Targeting an Older Java Version

If the program needs to be compatible with older versions of Java as a business requirement, compiling it accordingly would be the most sensible solution. This can be accomplished either by using an older JDK compiler, or by specifying the target version on a newer JDK compiler. Using the terminal command javac -target 8 com/rollbar/ExampleApp.java by specifying the targeted JDK version with the -target or alternatively the -release flag, will instruct the compiler to produce bytecode compatible with that version (Java 8 in this example).

This solution should work universally across different JDKs and compilers, so long as the target version is the same or older than that of the compiler, and given that the source code syntax is compatible with the target version. In instances where this isn’t the case, refactoring the code before compiling it might be necessary.

Working with IDEs

All major IDEs have configuration settings where one can specify which JDK and JRE versions to use, down to a project level. Newer IDEs even allow downloading newer versions directly through their graphical user interfaces which makes setting up a Java project a breeze, even if just for recompiling it. For this specific purpose, a setting normally called “Project language level” or “Compiler compliance level” can be tweaked, the project rebuilt/recompiled, and the aforementioned UnsupportedClassVersionError error resolved without ever leaving the IDE. An example for where to find this setting in JetBrains IDEs is shown below.

Jetbrains Intellij Idea IDE: Project Settings -> Language Level

Figure 3: JetBrains IntelliJ IDEA: Project Settings → Project language level

Maven Projects

When dealing with Maven projects, which the majority of both small and large enterprise Java programs are, it is possible to control the Java version targeted by the compilation process from the Maven configuration, i.e. Maven Project Object Model (POM) file. The relevant settings are shown in the Figure below.

Note that while it is possible to control the source and target versions independently, it is recommended to set them to equal values, as backward compatibility of the compiled bytecode cannot be guaranteed [8].

<project xmlns="http://maven.apache.org/POM/4.0.0"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
...
   <properties>
       <maven.compiler.source>17</maven.compiler.source>
       <maven.compiler.target>8</maven.compiler.target>
   </properties>
...
</project>
Figure 4: Maven POM file compiler properties

Conclusion

The UnsupportedClassVersionError error is a critical Java runtime error thrown during the class linking phase at the very beginning of a program’s execution. This error occurs when attempting to run some code, usually a full-fledged pre-compiled program, on a platform that has a JRE older than the one the code was compiled on. Resolving the UnsupportedClassVersionError error involves either updating the JRE on the target machine or, if backward compatibility is needed, recompiling the program to target the older JRE. Modern IDEs make this process easy with their built-in tools and configuration settings, which is not to say that the same cannot be accomplished without them, as has been explained in this article.

Track, Analyze and Manage Errors With Rollbar

Rollbar in action

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 error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!

References

[1] Rollbar, 2021. How to Fix «Illegal Start of Expression» in Java. Rollbar Editorial Team. [Online]. Available: https://rollbar.com/blog/how-to-fix-illegal-start-of-expression-in-java/. [Accessed Jan. 8, 2022]

[2] Oracle, 2021. Chapter 5. Loading, Linking, and Initializing. Oracle Corporation and/or its affiliates. [Online]. Available: https://docs.oracle.com/javase/specs/jvms/se17/html/jvms-5.html. [Accessed Jan. 8, 2022]

[3] Oracle, 2021. Error (Java SE 17 & JDK 17). Oracle and/or its affiliates. [Online]. Available: https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Error.html. [Accessed Jan. 8, 2022]

[4] Oracle, 2021. LinkageError (Java SE 17 & JDK 17). Oracle and/or its affiliates. [Online]. Available: https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/LinkageError.html. [Accessed Jan. 8, 2022]

[5] Oracle, 2021. ClassFormatError (Java SE 17 & JDK 17). Oracle and/or its affiliates. [Online]. Available: https://docs.oracle.com/javase/9/docs/api/java/lang/ClassFormatError.html. [Accessed Jan. 8, 2022]

[6] Oracle, 2021. UnsupportedClassVersionError (Java SE 17 & JDK 17). Oracle and/or its affiliates. [Online]. Available: https://docs.oracle.com/javase/9/docs/api/java/lang/UnsupportedClassVersionError.html. [Accessed Jan. 8, 2022]

[7] Oracle, 2011. Installing the JDK Software and Setting JAVA_HOME. Oracle and/or its affiliates. [Online]. Available: https://docs.oracle.com/cd/E21454_01/html/821-2531/inst_jdk_javahome_t.html. [Accessed Jan. 8, 2022]

[8] E. Punzalan, 2019. Apache Maven Compiler Plugin – Setting the -source and -target of the Java Compiler. The Apache Software Foundation. [Online]. Available: https://maven.apache.org/plugins/maven-compiler-plugin/examples/set-compiler-source-and-target.html. [Accessed Jan. 8, 2022]

  • Ошибка exception in thread main java lang noclassdeffounderror javax xml bind datatypeconverter
  • Ошибка exception in server tick loop
  • Ошибка exception in exception handler властелин колец
  • Ошибка exception in exception handler command and conquer 3
  • Ошибка exception has been thrown by the target of an invocation