Exception handling and assigning final member variables

R

Robert

I have a class which needs to take a string as input in its
constructor. I want to parse the string into constant member
variables, but this does not appear to work due to the way exception
handling is interpreted. Essentially, we have:

public class Foo {
public Foo(String input) {
try {
p = Integer.parseInt(input);
} catch(Exception e) {
p = 1;
}
}
private final int p;
}

This fails because the compiler thinks p might already be assigned:
[javac] Compiling 3 source files to C:\pig\build\classes
[javac] C:\pig\src\Foo.java:6: variable p might already have been
assigned
[javac] p = 1;
[javac] ^
[javac] 1 error

Is there another way to do this, or will I have to content myself with
not declaring p as final? I suppose I could always make a tempP and
assigned p that, but I would hope there is a more elegant way to do
this.
 
J

Joshua Cranmer

Robert said:
I have a class which needs to take a string as input in its
constructor. I want to parse the string into constant member
variables, but this does not appear to work due to the way exception
handling is interpreted. Essentially, we have:

public class Foo {
public Foo(String input) {
try {
p = Integer.parseInt(input);
} catch(Exception e) {
p = 1;
}
}
private final int p;
}

Try this:

public Foo(String input) {
int pValue;
try {
pValue = Integer.parseInt(input);
} catch (Exception e) {
pValue = 1;
}
p = pValue;
}

Alternatively, you could do this:

p = isValidInput(input) ? Integer.parseInt(input) : 1;
 
M

Mike Schilling

Joshua said:
Try this:

public Foo(String input) {
int pValue;
try {
pValue = Integer.parseInt(input);
} catch (Exception e) {
pValue = 1;
}
p = pValue;
}

Alternatively, you could do this:

p = isValidInput(input) ? Integer.parseInt(input) : 1;

Or

p = parseIntegerWithDefault(input, 1);

static int parseIntegerWithDefault(String str, int defVal)
{
try
{
return Integer.parseInt(str);
}
catch (Exception ex)
{
return defVal;
}
}
 

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

Similar Threads


Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,049
Latest member
Allen00Reed

Latest Threads

Top