Getting ExceptionInIntilizerError - java

while i am trying to run the following code iam getting ExceptionInInitilizerError instead of NullPointerException. why?
static
{
String s= null;
System.out.println(s.length());
}

Static blocks are the part of class code in java which are called when the class is loaded for the first time . If you carefully look at the exception you receive :
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.NullPointerException
at Main.Test.<clinit>(Test.java:8)
You have a NullPointerException wrapped in an ExceptionInitializerError.
Hence you received a NullPointerException and because that error occurred at a space where normal execution further was not possible , as a result you got ExceptionInitializaterError

When you use the static initializer block, errors are not handled as they would be in the rest of your code. When an error is thrown in the initializer block, the JVM throws java.lang.ExceptionInInitializerError. This will also occur when initialization of a static variable fails.

This is because loader is seeing error when initializing this class. If you see internal stack trace, you will find NullPointerException. But since it was the process of initializing class when loader saw the error, you are seeing this 'ExceptionInInitilizerError'.

Related

what causes java.lang.NoClassDefFoundError to occur randomly?

We've been getting NoClassDefFoundError in our server randomly. It Occasionally throws this error, and most of the time it runs without throwing any issue. What could be the reason for such weird behavior? Below is the exception.
java.lang.NoClassDefFoundError: Could not initialize class com.github.junrar.Archive
at org.apache.tika.parser.pkg.RarParser.parse(RarParser.java:75)
at org.apache.tika.parser.CompositeParser.parse(CompositeParser.java:280)
at org.apache.tika.parser.CompositeParser.parse(CompositeParser.java:280)
at org.apache.tika.parser.AutoDetectParser.parse(AutoDetectParser.java:143)
at org.apache.tika.Tika.parseToString(Tika.java:527)
at org.apache.tika.Tika.parseToString(Tika.java:602)
at com.xxx.attachment.AttachmentExtractionAPI.parse(AttachmentExtractionAPI.java:108)
com.github.junrar.Archive is present in the same jar which contains other tika dependencies.
I tried looking into the source of Archive.java. Looking for some possible runtime exception in static blocks. But it doesn't have a static block itself. What could have made this to throw exception randomly and run without any problem at times?
EDIT:-
We use ant for building. Below is the part of ant.properties that controls the dependencies of tika. Junrar is available as part of the tika.
tika_jar_file=${prod_home}/tikalib/tika-app-1.24.jar
tika_jar_srcdir=${tp_pkg}/tika
tika_jar_includes=**
tika_jar_excludes=org/apache/tika/parser/** org/apache/xerces/** org/apache/html/** org/apache/wml/** org/apache/xml/** org/xml/sax/** org/apache/xmlcommons/** javax/xml/** org/w3c/dom/**
tika_update_jar_file=${prod_home}/tikalib/tika-app-1.24.jar
tika_update_jar_srcdir=${tp_pkg}/tika
tika_update_jar_includes=org/apache/tika/parser/asm/** org/apache/tika/parser/chm/** org/apache/tika/parser/code/** org/apache/tika/parser/epub/** org/apache/tika/parser/html/** org/apache/tika/parser/iwork/** org/apache/tika/parser/mail/** org/apache/tika/parser/mbox/** org/apache/tika/parser/microsoft/** org/apache/tika/parser/odf/** org/apache/tika/parser/pdf/** org/apache/tika/parser/pkg/** org/apache/tika/parser/rtf/** org/apache/tika/parser/strings/** org/apache/tika/parser/txt/** org/apache/tika/parser/utils/** org/apache/tika/parser/xml/** org/apache/tika/parser/*.* org/apache/tika/parser/image/** org/apache/tika/parser/ocr/** org/apache/tika/parser/csv/** javax/xml/bind/**
tika_update_jar_excludes=
tika_update_jar_update=true
The key to this is understanding the error message:
java.lang.NoClassDefFoundError: Could not initialize class
com.github.junrar.Archive
Note that it says that it cannot initialize the class. There are a few reasons why a class cannot be initialized. These include:
An unchecked exception was thrown (and not handled) during the initialization of this class. If this has occurred, then there should be an earlier exception and stacktrace that tells you what exception was thrown and where.
This class has static dependencies on another class that failed initialization. There should be an earlier exception and stacktrace for that failure.
Possibly there is a dependency issue, though I would have expected a different exception message in that case.
The reason of NoClassDefFoundError is that two different jar of your project depend on the same jar with different version.So you can use the ide to excludes the jar in your pom.

Error — Unhandled exception type Exception

I'm currently creating a plugin for a game and for some unknown reason, I'm getting an error when I initialize the variable dbManager.
The variable is the second one that's being initialized and it's at the top of my class.
The line giving the error is:
static DBManager dbManager = DBManager.getInstance();
The whole class can be found here.
It invokes DBManager.
I tried wrapping it in try, catch blocks but that in itself gave it's own error. Eclipse isn't giving any auto correct suggestions either.
The error I'm getting is Unhandled exception type Exception. As this is a plugin, I'm currently unable to test this code to get any stacktrace.
What can I do to fix the error.
Use a static block to initialize this variable:
static DBManager dbManager;
static {
try {
dbManager = DBManager.getInstance();
}
catch (Exception e) {
throw new RuntimeException("Unable to geta DBManager instance", e);
}
}
I would not use a library which uses the raw Exception class to signal errors, though. Using non-final static fields as you're doing is another design smell.
Although I cant see the code from DBManager, this error says that there is unhandled exception this means DBManager.getInstance() throws exception and you could not use it like what you did in the link. you must handle the exception. It is better to get instance in your constructor and handle the exception ( at least with a try/catch) in there.

Unhandled Exception error unresolved compilation

public void useSkill(Champion target, int skillIndex, boolean enemy) throws UtilitiesException {
if (champSkills[skillIndex].getManaCost() > this.currentMana) {
throw new RequirmentNotMetException("Not Enough mana");
}
I would like to throw a requirmentNotMetexception (which extends the utilitiesException) with message "not enough mana".
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type UtilitiesException
at eg.edu.guc.lol.game.champions.Tank.useSkill(Tank.java:27)
at eg.edu.guc.lol.game.champions.asfasf.main(asfasf.java:33)
I want to use exceptions to show the user that the champion has no mana instead of using an if/else statement checking the mana of the champion and printing not enough mana.
Somebody in the call stack has to handle the RequirmentNotMetException, or every method on the call stack has to declare that it throws the exception (or a parent), or the exception has to extend RuntimeException. Evidently, your main method is not declared as throwing it, and I wouldn't expect it to. So, check up the call chain, identify who should handle the exception, have that method handle it, and have everything in between declare itself as throwing it.
Your useSkill method looks fine. It declares the exception type in the throws clause of the method signature, so the problem is likely where this method is invoked. It looks to me like you're getting the error runtime, which might indicate that you have not recompiled all the classes using the Tank class after you have changed the signature. Still, you need to either catch the exception where you're using the useSkill method, or just pass it on by declaring those methods to throw that exception type as well.
Either you have not imported the UtilitieException or your UtilitiesException class has errors.

Throwing Java exception in JRuby and catching it in Java

I have created my own UI component in Java. It has model and a few of model's methods can throw my exception called ModelException. I want to use this component in JRuby but I can't raise my ModelException:
raise ModelException # it cause TypeError: exception class/object expected
So I tried to create method throwing ModelException in Java and then invoke it in JRuby:
public class ScriptUtils {
private ScriptUtils() {
}
public static void throwModelException(ModelException e)
throws ModelException {
throw e;
}
}
but when I call throwModelException from JRuby I get:
org.jruby.exceptions.RaiseException: Native Exception: 'class app.ui.ModelException'; Message:
; StackTrace: app.ui.ModelException
...
Caused by: app.ui.ModelException
this native exception cannot be handled by Java code.
Any ideas how to throw Java exception in JRuby and catch it in Java?
This is a complete re-write of my original answer as I originally mis-read your question!
You can raise Java exceptions and catch them in JRuby but you need to be a bit careful how you call raise:
raise ModelException
Will cause a type error (as you saw) because to JRuby ModelException looks like a plain constant. Remember that in Ruby class names are constants. You can raise direct subclasses of Ruby Exception like this, e.g.:
raise RuntimeError
But I think such subclasses are a special case. Those that are actually Java classes you need to call with a constructor:
raise ModelException.new
Or whatever constructor/s you have for that class. An instance of ModelException, in JRuby, is a subclass of Exception because JRuby creates it as such, but the Java class itself isn't. All this is assuming that you have imported your ModelException class correctly.
As for your second example, I couldn't replicate that error at all. As long as I created the exception object correctly, as above, it worked and I didn't see any complaints about "Native Exception" at all. So I'm not sure what is happening there, sorry.

java static inner class initialization errors

Context:
java.io.File class has a static inner class method as follows:
LazyInitialization.temporaryDirectory();
[EDITED to add some more code]
My code below eventually calls the above line of code. An exception is thrown from within the temporaryDirectory() method, which in my context is fine/expected.
try {
File tempFile = File.createTempFile("aaa", "aaa");
} catch (Exception e) {
// handle exception
}
Then, when I next invoke the same method (createTempFile) again, I get a "java.lang.NoClassDefFound error - Could not initialize class java.io.File$LazyInitialization"
Question:
I assumed that the inner class LazyInitialization should have been loaded by the class loader when its static method was invoked, even though the inner method threw an exception. Yet, why am I seeing the NoClassDefFound error when invoking the second time? Is the original assumption incorrect?
When a static initialization code throws a runtime exception, it is wrapped by ExceptionInInitializerError and thrown in the context of the code triggering the class loading (if its an Error exception, it is not wrapped). At this point, the class failed loading. Therefore, any attempt to use it later will cause a NoClassDefFoundError.
Perhaps this is what you experience.

Categories