java static inner class initialization errors - java

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.

Related

Why throwing an exception tries to loads the class which extends Exception (though it is not executed) but not a regular class

I have the below classes.
I have manually compiled the classes using javac and ran the Driver class.
Later removed the entity.class and MyCustomException.class and ran the app like below.
java Driver test
The below error is complained about MyCustomException is missing but not about the Entity class. So, not clear why JRE complaining about MyCustomException class but not the Entity class.
Indeed I have removed code throw new MyCustomException(); but I did not encounter error about Entity class.
Caused by: java.lang.NoClassDefFoundError: com/techdisqus/exception/MyCustomException
Please note that the IF condition will NOT be executed as I am passing command argument as test
Why is it throwing an exception is causing to load the MyCustomException which would be never executed but the JVM does not load any other regular class unless condition is satisfied, as here Entity class here. Please check Driver.java below.
MyCustomException.java
public class MyCustomException extends RuntimeException {
}
Entity.java
public class Entity {
}
Driver.java
public class Driver {
public static void main(String[] args) {
String s = args[0];
if("true".equals(s)){
Entity entity = new Entity(); // This is not loaded, unless s is true
throw new MyCustomException(); // this is loaded even s is NOT true.
}else{
System.out.println("success");
}
}
}
Thanks for help
(this is an educated guess; I'm by no means an expert on JVM internals)
I assume the error happens during verification, when the loaded class undergoes some sanity checks so the runtime can make some assumptions later.
One of the checks is a typecheck of bytecode instructions. Specifically athrow:
An athrow instruction is type safe iff the top of the operand stack matches Throwable.
So at this point, the classloader has to load MyCustomException to check whether it extends Throwable

Getting ExceptionInIntilizerError

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'.

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.

Categories