Nissa
Nissa

Reputation: 215

Continue after catching exception (Android/Java)

I want to convert an input string to long:

String inputStr = inputText.getText().toString();
Long inputNumber = Long.valueOf(inputStr);
// do something with inputNumber

However if the user input a string with alphabets the valueOf() will throw some exception to cause the program to crash.

On the other hand if I build a try-catch block around valueOf(), I get a "cannot resolve symbol inputNumber" error. If I declare Long inputnumber outside the block I get a "this variable may not be initialized" error.

I want to just output an error message in a textView for incorrect inputStr, and continue the program as usual. How to do this?

Upvotes: 0

Views: 787

Answers (2)

Naman Gala
Naman Gala

Reputation: 4692

I would prefer to use util class and declare a boolean method and use it to check if entered number is number or not. This is reusable code.

public class StringUtil {

    public static boolean isNumeric(String str) {
        boolean returnVal = false;
        if (isNotEmpty(str)) {
            try {
                Long.parseLong(str);
                returnVal = true;
            } catch (NumberFormatException e) {
                returnVal = false;
            }
        }
        return returnVal;
    }
}

In your method

String inputStr = inputText.getText().toString();
Long inputNumber = null;
if (StringUtil.isNumeric(inputStr)) {
    inputNumber = Long.valueOf(inputStr);
    // do something with inputNumber
} else {
     // either notify user or whatever you want to do.
}

If you can use apache commons then you can use its NumberUtils.isNumber(String str)

String inputStr = inputText.getText().toString();
Long inputNumber = null;
if (NumberUtils.isNumber(inputStr)) {
    inputNumber = Long.valueOf(inputStr);
    // do something with inputNumber
}

Upvotes: 0

beresfordt
beresfordt

Reputation: 5222

Declare and initialise inputNumber outside of try/catch:

Long inputNumber = null;
try {
    inputNumber = Long.valueOf(inputStr);
}
catch (NumberFormatException e) {
    // handle exception
}

Upvotes: 5

Related Questions