Error — Unhandled exception type Exception - java

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.

Related

Unhandled exception type Exception

This is a simplified class that describes my problem:
public class Main {
enum Test{
First(method()){ // Unhandled exception type Exception
// ...
};
Test(Object obj){
//...
}
}
static Object method() throws Exception{
// ...
if (someCondition){
throw new Exception();
}
}
}
Above someCondition depends on device and some situations and I can not decide in about it now, also as you can see, I do not want to catch Exception in method.
Yes. It is a compilation error.
No. There is no special syntax to deal with this.
I do not want to catch Exception in method.
Unfortunately if you throw a checked exception, it has to be caught further up the call stack. That is a fundamental design principal for the Java language, and one that the compiler enforces strictly.
In this, case there is no way to catch the checked exception. Hence, if you are going to call a method in enum constant parameter (as per your code), the method cannot throw a checked exception1.
Here is a possible workaround, though this is probably a bad idea:
public class Main {
enum Test{
First(methodCatchingException()){
// ...
};
Test(Object obj){
//...
}
}
static Object method() throws Exception{
// ...
if (someCondition){
throw new Exception();
}
}
static Object methodCatchingException() {
try {
return method();
} catch (Exception ex) {
throw new SomeRuntimeException("the sky is falling!", ex);
}
}
}
Another way to look at this problem is to ask yourself what should happen with the exception if the compiler let you write that ... and an exception was thrown? Where would it go?
You can't catch it ... because the enum initialization is like a static initialization.
If the Java runtime completely ignored the thrown exception, that would be really bad.
If the Java runtime crashed, then the model of checked exceptions is broken.
So, what this is saying to me is that the Java language design is right, the Java compiler is right ... and the real problem here is in your application design:
You should not be propagating a checked exception here. If an exception occurs in this context it is categorically NOT a recoverable error.
Maybe it is inadvisable to use an enum for this ... because of the potential for non-recoverable initialization errors.
(Note that if this method call terminates due to an unchecked exception, it will turn it into an ExceptionInInitializerError. In addition, the JVM will mark the enum class as uninitializable, and will throw an NoClassDefFoundError if your application attempts to use it; e.g. via Class.forName(...).)
I assume that Exception is used here for illustration purposes. It is a bad thing to declare methods as throws Exception or to throw new Exception(...)
1 - I had a look at the JLS for something to back this up. As far as I can tell, the spec does not mention this situation. I'd have expected to see it listed in JLS 11.2.3. However, it is clear that a compiler cannot allow a checked exception to propagate at that point as it would "break" the model of how checked exceptions work.
I don't think you want to be throwing a checked exception here (which is what Exception is). The reason: you're invoking the call of method inside of the constructor of Test. There's really not a clean way to deal with it.
While the obvious choice here is to switch to RuntimeException, I want you to reconsider throwing the exception in the first place. Since your enum will only ever have First declared in it, does it really make sense for it to throw an exception when it's being instantiated? Personally, I don't think it does; whatever dangerous operation it's doing should be deferred until you want to invoke it, and then would you want to throw your exception.

Android - general exception catcher

I'm trying to integrate Facebook into my app so I followed all the instructions. When running it, after onResume event finishes, I get an exception that I can't catch from my code.
Is there a way to set a general exception catcher so no matter what, it will catch it?
The emulator does not throw any exception at all so I can't use it for this
Update: I found it here: Using Global Exception Handling on android
The error came from Facebook itself and it is related to working with proguard
try this solution:
create a class that implement Thread.UncaughtExceptionHandler (this
class going to handle with the uncaughtExceptions), lets call this
class ExceptionHandler.
create a class that extends Application,
lets call this class App, and don't forget to declare this in the
manifest file under application tag: android:name="your_package_path.App"
in your App class override the method onCreate(), and add this line: Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));
The Throwable class is the superclass of all errors and exceptions in the Java language.
If you catch a throwable you can catch all kind of errors and exceptions.
try {
// code
} catch(Throwable e) {
// handle throwable
}
However this is strongly not recommended and bad practise/design. You should never catch generic errors and exceptions. You should analyse your specific exception and solve the problem instead of simply ignoring it with try/catch!
There is a base Exception class. So if you do like this:
try {
...anything...
}catch(Exception e) {
e.printStackTrace();
}
you'll catch any exception that is thrown by any method called from within the try block.
But remember that exceptions aren't always thrown. Sometimes there's just no result to return, or something.

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.

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.

Why can I "fake" the stack trace of an exception in Java?

If I run the following test, it fails:
public class CrazyExceptions {
private Exception exception;
#Before
public void setUp(){
exception = new Exception();
}
#Test
public void stackTraceMentionsTheLocationWhereTheExceptionWasThrown(){
String thisMethod = new Exception().getStackTrace()[0].getMethodName();
try {
throw exception;
}
catch(Exception e) {
assertEquals(thisMethod, e.getStackTrace()[0].getMethodName());
}
}
}
With the following error:
Expected :stackTraceMentionsTheLocationWhereTheExceptionWasThrown
Actual :setUp
The stack trace is just flat out lying.
Why isn't the stack trace rewritten when the exception is thrown? I am not a Java dev, and maybe I'm missing something here.
The stack trace is created when the exception is instantiated, not when it is thrown. This is specified behaviour of the Java Language Specification
20.22.1 public Throwable()
This constructor initializes a newly created Throwable object with null as
its error message string. Also, the method fillInStackTrace (§20.22.5) is
called for this object.
....
20.22.5 public Throwable fillInStackTrace()
This method records within this Throwable object information about the
current state of the stack frames for the current thread.
I don't know why they did it that way, but if the specification defines it like that, it is at least consistent on all the various Java VMs.
However, you can refresh it by calling exception.fillInStackTrace() manually.
Also note that you should use Thread.currentThread().getStackTrace() instead of using new Exception().getStackTrace() (bad style).
The stacktrace of the exception is filled in at creation time of the exception. Otherwise it would be impossible to catch an exception, handle it and rethrow it. The original stacktrace would get lost.
If you want to force this you have to call exception.fillInStackTrace() explicitly.
Because you didn't ask that that stack trace be rewritten. It was set when you created it in the setUp method, and you never did anything to alter it.
The Exception class doesn't give you any opportunity to set the method name; it's immutable. So there's no way that I know of where you could re-set the method name, unless you wanted to resort to something heinous like reflection.
Your #Test annotation doesn't tell me if you're using JUnit or TestNG, because I can't see the static import, but in either case you can run a test to see if a particular exception is thrown by using the "expected" member in the #Test annotation.
You wouldn't want throwing an exception to alter the stack track or you couldn't re-throw an exception safely.
public void throwsException() {
throw new RuntimeException();
}
public void logsException() {
try {
throwsException();
} catch (RuntimeException e) {
e.printStrackTrace();
throw e; // doesn't alter the exception.
}
}
#Test
public void youCanSeeTheCauseOfAnException(){
try {
logsException();
} catch(Exception e) {
e.printStrackTrace(); // shows you the case of the exception, not where it was last re-thrown.
}
}
The stack trace in the exception corresponds to the "new" operation, nothing else.
I think the assumption is that you won't be instantiating an exception unless you are in the process of throwing it, so why pay the price to get the stack trace twice?
It would be difficult to recreate the stack trace while throwing it, as that is just sending the object out.
The exception should be fully setup before the throw, so part of the instantiation is to get the stack trace.
UPDATE:
You can call fillInStackTrace() to resolve this.

Categories