NumberFormatException

StupidAttack

Bekanntes Mitglied
Huhu 🙂

Je nach Programmablauf, wirft folgende Zeile Code eine NumberformatException:

Java:
int dummy = Integer.parseInt(action_id_container.get(i));

Ich will sie jedoch nicht in einen try catch Block einbauen, weil sonst der ganze Rest der Methode nicht mehr ausgeführt wird.

Wie kann ich sonst Überprüfen ob eine Methode einen Integer als Zahl zurückgibt?


Danke
 
Java:
private static boolean isInteger(String s)
{
    try
    {
        Integer.parseInt(s);
        return true;
    }
    catch (NumberFormatException e)
    {
        return false;
    }
}
 
Ich vermute mal

action_id_container.get(i)

liefert einen String

Also

String str = action_id_container.get(i);
str untersuchen ob es ein int ist (nur ziffern und zuvorderst optional ein -)
parseInt aufrufen falls str ok ist
 
Java:
private static boolean isInteger(String s)
{
    try
    {
        Integer.parseInt(s);
        return true;
    }
    catch (NumberFormatException e)
    {
        return false;
    }
}

Ja, dann werde ich die boolschen Werte als Variablen abspeichern und am Ende der Funktion zurückgeben, damit in jedem Falle die Funktion ganz ausgeführt wird.

Thx (ohne try/catch gehts nicht?)
 
>(ohne try/catch gehts nicht?)

Nein. Man könnte aber auf den Wrapper zurück greifen. Wird null zurückgegeben, wars keine Zahl.

Java:
public static Integer toInteger(String number) {
	if (number == null) {
		return null;
	}
	try {
		return Integer.decode(number);
	} catch (NumberFormatException nfe) {
		return null;
	}
}
 
Ich will sie jedoch nicht in einen try catch Block einbauen, weil sonst der ganze Rest der Methode nicht mehr ausgeführt wird.



Java:
int dummy = 0;
           try {
              dummy = Integer.parseInt(action_id_container.get(i)); 
         } catch (NumberFormatException e) {
            // hier eine warn message, loggen oder sonst was
         }
//bei fehler wird hier weitergemacht...
 
man könnte vllt auf eine RegEx abprüfen und mit Integer.MAX_VALUE vergleichen (dann aber eher mit einem BigInteger). Ob das dann besser ist, sei mal dahingestellt 🙂
 
Die beste Lösung wäre, es möglichst gar nicht zu der Exception kommen zu lassen.
Warum ist [c]action_id_container.get(i)[/c] keine gültige Zahl? Ist das ein Bug? Wenn ja, beheben. Wenn nein, hat man vielleicht ein Designproblem...
 
Es geht auch ohne try/catch. Aber es ist unangemessen viel aufwändiger. (BTW: Zumindest solltest du jeden Text erst 'trim'men, bevor du ihn an Integer.parseInt schickst:

String text = irgendwoher();
int i = Integer.parseInt(text.trim());
 


Java:
int dummy = 0;
           try {
              dummy = Integer.parseInt(action_id_container.get(i)); 
         } catch (NumberFormatException e) {
            // hier eine warn message, loggen oder sonst was
         }
//bei fehler wird hier weitergemacht...

Jap, habe ich nach meinem Post auch realisiert. Ich dachte das, weil ich bis anhin die exception weitergeleitet habe, da wird dann die funktion abgebrochen.

Die beste Lösung wäre, es möglichst gar nicht zu der Exception kommen zu lassen.
Warum ist action_id_container.get(i) keine gültige Zahl? Ist das ein Bug? Wenn ja, beheben. Wenn nein, hat man vielleicht ein Designproblem...

Ist nicht mein Bug. Wenn das Browsergame meint, es müsse die Session beenden und ich dann kein Response Context (html) mehr bekomme, kann ich es nur so überprüfen. Natürlich kann ich das Error Handling in diesem Falle auch über die Statuscodes (200 OK) machen , aber diese sind nicht verlässlich und ich müsste zu Testzwecken wieder requests abschicken...
 
ohne try/catch könnte man es vllt so machen:
Java:
	public static boolean isInteger(String s) {
		if (!s.matches("-?[0-9]+"))
			return false;
		BigInteger i = new BigInteger(s);
		return (new BigInteger(String.valueOf(Integer.MAX_VALUE)).compareTo(i) >= 0 && new BigInteger(String.valueOf(Integer.MIN_VALUE)).compareTo(i) <= 0);
	}

ob das performant ist. kp 🙂

edit: geht bestimmt aber auch ohne BigInteger und nur mit RegEx. Bei Double geht es ja auch:
Double (Java 2 Platform SE 5.0)

allerdings schon eine ziemlich lange RegEx 😉
 
Zuletzt bearbeitet:
ob das performant ist. kp 🙂

Exceptions brauchen auch ganz schön viel Zeit - ich hab jetzt nicht nachgesehen was parseInt intern macht, aber es könnte etwas ähnliches sein wie du vorschlägst.

Nur liesse sich int vermutlich ohne regexp schneller prüfen.
position 0 : '-' '0'...'9'
alle weiteren '0'...'9' (loop von 1..ende )

fertig
 
alle weiteren mit Character.isDigit. aber gut, das ist Microbenchmark und da greif ich persönlich irgendwie lieber zu RegEx. Glaube nicht, dass parseInt intern mit BigInteger arbeitet. Wird wohl eher eine komplexe RegEx oder so sein. Bei Double gehts ja auch und da ist's nochmal wesentlich komplexer...
 
Java:
    public static int parseInt(String s, int radix)
		throws NumberFormatException
    {
        if (s == null) {
            throw new NumberFormatException("null");
        }

	if (radix < Character.MIN_RADIX) {
	    throw new NumberFormatException("radix " + radix +
					    " less than Character.MIN_RADIX");
	}

	if (radix > Character.MAX_RADIX) {
	    throw new NumberFormatException("radix " + radix +
					    " greater than Character.MAX_RADIX");
	}

	int result = 0;
	boolean negative = false;
	int i = 0, max = s.length();
	int limit;
	int multmin;
	int digit;

	if (max > 0) {
	    if (s.charAt(0) == '-') {
		negative = true;
		limit = Integer.MIN_VALUE;
		i++;
	    } else {
		limit = -Integer.MAX_VALUE;
	    }
	    multmin = limit / radix;
	    if (i < max) {
		digit = Character.digit(s.charAt(i++),radix);
		if (digit < 0) {
		    throw NumberFormatException.forInputString(s);
		} else {
		    result = -digit;
		}
	    }
	    while (i < max) {
		// Accumulating negatively avoids surprises near MAX_VALUE
		digit = Character.digit(s.charAt(i++),radix);
		if (digit < 0) {
		    throw NumberFormatException.forInputString(s);
		}
		if (result < multmin) {
		    throw NumberFormatException.forInputString(s);
		}
		result *= radix;
		if (result < limit + digit) {
		    throw NumberFormatException.forInputString(s);
		}
		result -= digit;
	    }
	} else {
	    throw NumberFormatException.forInputString(s);
	}
	if (negative) {
	    if (i > 1) {
		return result;
	    } else {	/* Only got "-" */
		throw NumberFormatException.forInputString(s);
	    }
	} else {
	    return -result;
	}
    }
 
EDIT: Der schnelle Joe hat mich wieder einmal überrundet 🙂

Habt ihr gewusst dass "+123" kein integer ist???? Das ist aber eher peinlich.

Code:
Exception in thread "main" java.lang.NumberFormatException: +123

Ansonsten läuft es ziemlich genau so wie ich es auch implementiert hätte - nichts kompliziertes wie regexp u.ä.

EDIT: Java code gelöscht ...
 
Zuletzt bearbeitet:

Zurück
Oben