Re: intialising static finals with exceptions
Roedy Green wrote:
On Thu, 17 Jan 2008 09:18:24 -0500, Lew <lew@lewscanon.com> wrote,
quoted or indirectly quoted someone who said :
Initialize it in a static initialization block, and make sure that something
reasonable happens in the catch{} block.
see http://mindprod.com/jgloss/initialisation.html#CATCH22 for a
concrete example.
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.
--
Lew