Initializing final variables

C

Christoph Burschka

I'm declaring a constant object in my class definition, whose
constructor throws an exception. Note that the exception never actually
gets thrown - my argument ensures that.

Apparently, I can't use try-catch blocks outside a method, so I can't
initialize this value in the class declaration. But if I don't
initialize it there, I can't declare it final.

Does this just mean I can't initialize final variables with
exception-throwing constructors, or is there a solution?

--cb
 
T

Tom Hawtin

Christoph said:
I'm declaring a constant object in my class definition, whose
constructor throws an exception. Note that the exception never actually
gets thrown - my argument ensures that.

Apparently, I can't use try-catch blocks outside a method, so I can't
initialize this value in the class declaration. But if I don't
initialize it there, I can't declare it final.

private static final MyClass thing;
static {
try {
thing = new MyClass();
} catch (SomeException exc) {
throw new Error();
}
}

or

private static final MyClass thing = makeThing();
private static MyClass MakeThing() {
try {
return new MyClass();
} catch (SomeException exc) {
throw new Error();
}
}

Tom Hawtin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top