Nicholas
Nicholas

Reputation: 578

Disable Error Prompt/Warning in Eclipse Java Neon

I am working with the following code in Eclipse:

public class Foo {
    public static final Bar bar = new Bar(20);
}

public class Bar {
    public int value;

    // This needs to be able to be called in places other than
    // just Foo, and there it will need to throw.
    public Bar(int value) throws Exception {
        if(value == 0) {
            throw Exception("Error. Value cannot be 0 when constructing Bar.");
        }
        return;
     }
}

This gives me an error message in Foo (line 2) which says, "Unhandled exception type Exception", even though in practice, this exception will never occur with this code. Can I disable this error in Eclipse so it doesn't bother me, or is there another way I can deal with this error?

Thanks ahead of time for the answers!

Upvotes: 0

Views: 447

Answers (2)

howlger
howlger

Reputation: 34135

This is a compiler bug that needs to be fixed to compile the Java code and is not an Eclipse issue: checked exceptions require an explicit handling in Java by surrounding it with try-catch or pass the exception (method/constructor throws ...).

If the class Bar cannot be changed, one possibility would be to use a private static method to initialize the constant bar (which should be named BAR according to the Java naming conventions):

public class Foo {

    public static final Bar BAR = initBar(20);

    private static Bar initBar(int value) {
        try {
            return new Bar(20);
        } catch (InvalidCharacterException e) {
            return null;
        }
    }

}

Upvotes: 1

The Confraternity
The Confraternity

Reputation: 21

Surround the constructor with a try/catch to catch the exception.

Like this:

public class Foo {

try {
    public static final Bar = new Bar(20);
}catch(InvalidCharacterException e) {
    e.PrintStackTrace();
}

Should fix your issue. Feel free to respond if it does not and I will try and help you further.

Upvotes: 0

Related Questions