intialising static finals with exceptions

R

Roedy Green

Is there a way to initialise a static final constant with an
expression that might trigger an exception?

I played with various ways but Javac thought it might not get
initialised, or it might get initialised twice or I was ignoring the
exception.
 
G

GArlington

Is there a way to initialise a static final constant with an
expression that might trigger an exception?

I played with various ways but Javac thought it might not get
initialised, or it might get initialised twice or I was ignoring the
exception.

Init it in the constructor inside try ... catch block?
 
T

Thomas Schodt

Roedy said:
Is there a way to initialise a static final constant with an
expression that might trigger an exception?

I played with various ways but Javac thought it might not get
initialised, or it might get initialised twice or I was ignoring the
exception.

class MyClass {
static final int FIXED;
static final int FIXEDdefaultvalue = 0;
static { // static constructor block - this goes into <clinit>
int tmp = FIXEDdefaultvalue;
try {
tmp = ForeignObject.mayThrow();
} catch (Exception ex) {
// ignore?
}
FIXED = tmp;
}
}

class ForeignObject {
static int mayThrow() throws Exception
{
return 1;
}
}
 
L

Lord Zoltar

Roedy said:
Is there a way to initialise a static final constant with an
expression that might trigger an exception?

I played with various ways but Javac thought it might not get
initialised, or it might get initialised twice or I was ignoring the
exception.

Have you tried using a static initializer for the class?
 
L

Lew

Init it in the constructor inside try ... catch block?

It's a *static final* field. Constructor initialization would fail miserably.

Initialize it in a static initialization block, and make sure that something
reasonable happens in the catch{} block.
 
L

Lew

Roedy said:

Another way around it is with a static initialize() method:

private static final VAR = initializeVar();

The mindprod example has a couple of problems that obscure its pedagogical
purpose:
try
{
static final URL WEBSITEURL = new URL( "http://mindprod.com" );
}
catch ( MalformedURLException e )
{
WEBSITEURL = null;
// will not compile with or without the above line.
}

This has syntax errors other than the possible duplicate assignment. Here's a
cleaned-up version that exhibits the catch-22:

static final URL WEBSITEURL;
static
{
try
{
WEBSITEURL = new URL( "http://mindprod.com" );
}
catch ( MalformedURLException e )
{
WEBSITEURL = null;
// will not compile with or without the above line.
}
}
~/projects/testit/src/testit/StatInitter.java:23: variable WEBSITEURL might already have been assigned
WEBSITEURL = null;
1 error

The proposed fix:
static final URL WEBSITEURL;

static
{

try
{
URL temp = new URL( "http://mindprod.com" );
}
catch ( MalformedURLException e )
{
temp = null;
// Will not complain because temp is not a static final.
}

WEBSITEURL = temp;
}

has a syntax error - the variable 'temp' goes out of scope at the end of the
try block, making it inaccessible to the catch block or the final assignment.
It should be scoped to the entire static block:

static final URL WEBSITEURL;
static
{
URL temp;
try
{
temp = new URL( "http://mindprod.com" );
}
catch ( MalformedURLException e )
{
temp = null;
// Will not complain because temp is not a static final.
}
WEBSITEURL = temp;
}

This static block would be embedded into the private static method suggested
above, if that route were taken.
 
R

Roedy Green

This has syntax errors other than the possible duplicate assignment. Here's a
cleaned-up version that exhibits the catch-22:

How embarrassing. That's what happens when I "clean up" real code to
make a teaching example without actually compiling it.

Thanks. Now fixed.
 
G

Gunter Herrmann

Hi!

Thomas said:
class MyClass {
static final int FIXED;
static final int FIXEDdefaultvalue = 0;
static { // static constructor block - this goes into <clinit>
int tmp = FIXEDdefaultvalue;
try {
tmp = ForeignObject.mayThrow();
} catch (Exception ex) {
// ignore?
}
FIXED = tmp;
}
}

class ForeignObject {
static int mayThrow() throws Exception
{
return 1;
}
}

or:

Interface ApplicationConstants
{
public static final Connection myFinalConnection
= Initial.getConnection();

}

Class Initial
{
public static Connection getConnection()
{
Connection returnValue = null;
try
{
returnValue = something();
}
catch (SQLException sqlex)
{
// some logging
}
return returnValue;
}
}


brgds
 
L

Lew

Roedy said:
How embarrassing. That's what happens when I "clean up" real code to
make a teaching example without actually compiling it.

You shouldn't be embarrassed. I am privileged to be able to contribute.
 
L

Lew

Gunter said:
Hi!



or:

Interface ApplicationConstants

lower-case "i" for the keyword 'interface'
{
public static final Connection myFinalConnection
= Initial.getConnection();

It's against the spirit of interfaces to implement things, in what they call
the Constant Interface Antipattern, and creates interesting risks.

<http://java.sun.com/docs/books/effective/>
Item 17.

Also, if you're initializing using the public static method of class Initial
anyway, why do you need the interface? Just use the Initial method.
}

Class Initial

The keyword 'class' is spelled with all lower-case letters.
 
R

Roedy Green

You might want to move the declaration of
URL temp;
outside the try block so it is still in scope when we want to use it
or did you leave that as an exercise for the reader?

arrgh. Do I have it right now? I am running a fever. My brain is a
fog.
 
D

Daniele Futtorovic

Is there a way to initialise a static final constant with an
expression that might trigger an exception?

I played with various ways but Javac thought it might not get
initialised, or it might get initialised twice or I was ignoring the
exception.

Just my (late) two cents, additionally to Thomas Schodt's solution:

If you do not wish to ignore the Exception which might possibly get
thrown, you can do so, by using something else than a checked exception.

For instance, an Error:

class Test {

public static final int CONSTANT;

static {
try {
CONSTANT = mayFail();
}
catch (Exception ex){
throw new Error(ex);
}
}

static int mayFail() throws Exception {
return 0;
}
}

A RuntimeException does it too, of course. IOW, the situation you
describe only ever applies when checked exceptions are involved.

DF.
 

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

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top