Try-Catch

Assume I have 3 Strings which potentially contain numeric values ...I intend to convert these Strings to a BigDecimal. If, for some reason one or more of the Strings do not contain a valid numeric value, I want to substitute a zero value....and then continue on processing the next assignment.

They question is if I can effectively use a try/catch to accomplish this

( without using a separate try/catch around each assignment. )

In the example below, the assignment to aBD and bBD would not occur since the NumberFormatException would engage after the first attempt

on assignment on cBD ...is there a way around this ?

Example:

String a= "900.12";

String b= "800.12";

String c= "XXX";

try {

BigDecimal cBD = new java.math.BigDecimal(c);

BigDecimal aBD = new java.math.BigDecimal(a);

BigDecimal bBD = new java.math.BigDecimal(b);

catch ( NumberFormatException nfe ) {

}

[965 byte] By [ramrod1460a] at [2007-10-1 22:09:04]
# 1

String a= "900.12";

String b= "800.12";

String c= "XXX";

BigDecimal cBD;

try {

cBD = new java.math.BigDecimal(c);

} catch ( NumberFormatException nfe ) {

cBD = new java.math.BigDecimal(0);

}

BigDecimal aBD;

try {

aBD = new java.math.BigDecimal(a);

} catch ( NumberFormatException nfe ) {

aBD = new java.math.BigDecimal(0);

}

BigDecimal bBD;

try {

bBD = new java.math.BigDecimal(b);

} catch ( NumberFormatException nfe ) {

bBD = new java.math.BigDecimal(0);

}

Caffeine0001a at 2007-7-13 8:22:26 > top of Java-index,Developer Tools,Debugging and Profiling Tool APIs...
# 2

And better yet.

public static void main(String[] args) throws Exception {

String a= "900.12";

String b= "800.12";

String c= "XXX";

BigDecimal cBD = formatBigDecimal(c);

BigDecimal aBD = formatBigDecimal(a);

BigDecimal bBD = formatBigDecimal(b);

}

static BigDecimal formatBigDecimal(String value) {

try {

return new java.math.BigDecimal(value);

} catch ( NumberFormatException nfe ) {

return new java.math.BigDecimal(0);

}

}

Caffeine0001a at 2007-7-13 8:22:26 > top of Java-index,Developer Tools,Debugging and Profiling Tool APIs...