user9821941
user9821941

Reputation:

NumberFormatException for Long

I have defined one variable as Long. And if someone passes String to that variable it throws NumberFormatException. How can i throw my own message. Like only Long values are allowed. I'm doing:

Long period; But instead of Long value someone entered String. Then it should through error

Upvotes: 0

Views: 106

Answers (4)

 VzrivPaket
VzrivPaket

Reputation: 1

You can write regexp for long. After that you should check your long string for regexp. If string does not match pattern then you can log error message.

String longRegexp = "^-?[0-9]{1,19}$";
if(!yourLong.matches(longRegexp )){
    //Log it.
}

Upvotes: 0

achAmháin
achAmháin

Reputation: 4266

You can define your own Exception:

class LongValueException extends Exception {

    public LongValueException () {
    }

    public LongValueException (String message) {
        super(message);
    }
}

Then call it in your try...catch:

try{
    Long.parseLong(yourString);
}
catch (NumberFormatException e){
    throw new LongValueException ("Only long can be used here");
}

Upvotes: 0

Vinit Mehta
Vinit Mehta

Reputation: 459

You can use like below.

try {
        ....////
    }
    catch (NumberFormatException nfe) {
        throw new NumberFormatException("The value you entered, " + value+ " is invalid.");
    }

Upvotes: 3

Karol Dowbecki
Karol Dowbecki

Reputation: 44952

Catch and re-throw your own exception

try {
  l = Long.parseLong(text);
} catch (NumberFormatException ex) {
  throw new IllegalArgumentException("Only long values are allowed", ex);
}

Upvotes: 0

Related Questions