How to avoid NoClassDefFoundError?

3

I'm developing a project that has many classes, and many .java files, and from time to time, from time to time, this problem happens, randomly. Let's say: A class that I used, is working perfectly, out of nowhere if it "rebels" and resolves to give that error.

Is there a way to "predict" and "avoid" this error, seeing that this is appearing randomly in my project?

I know how to solve the problem via code (so much so that there are several tutorials on this), but this project will be used in a company, and I will not have time to come and fix it every time the system resolves itself " rebel. "

    
asked by anonymous 15.06.2016 / 14:42

2 answers

2

The NoClassDefFoundError error occurs when a class exists, but Java ClassLoader can not load or initialize it properly.

This can occur in several situations, for example:

  • If you have a static initialization block or static attribute that throws some exception, so the class is not loaded.
  • If the class failed to load an imported class for any reason.

Since you are running the code in your IDE and resolve to rebuild the class, the problem may simply be that existing classes are not being recompiled as you make changes.

First, make sure NetBeans is set to compile classes to save the file .

If it does not resolve, use the Clean and Build Project option on all projects involved to force recompilation of the project.

If it still does not resolve, check your dependencies. If there are different versions of libraries in classpath , this means that you may now be running one version or another version and having random errors.

    
20.06.2016 / 08:07
2

According to the official Oracle documentation on this error:

  

Launched if the Java Virtual Machine or a ClassLoader instance tries to load into a class definition (as part of a normal method call or as part of creating a new instance using the new expression), and no class definition could be found.   The searched class definition existed when the currently running class was compiled, but the definition can no longer be found.

And if you want to take a closer look at the documentation you can see here / a>.

That is, this is caused when there is a class file that your code depends on and is present at compile time, but it was not found during execution. Look at differences in your build time and the classpaths runtime . p>

Why not use try-catch and put your code in whenever this error occurs, tidy up or at least show an error message?

try
{
// Código que irá aparacer caso não ocorra nenhum erro.
}
catch (NoClassDefFoundError e)
{
// Procure olhar no seu código se está instanciando de forma correta.
}

I advise you to look at the following links to learn how to solve, why they occur and how to prevent this error:

link

link

link

link

    
19.06.2016 / 03:52