JavaのNumberFormatExceptionついてサンプルコードで解説
今回はNumberFormatExceptionについてサンプルコードで解説します。
NumberFormatExceptionとは
数値に変換できない文字列が渡された場合に発生する例外です。
サンプルコード
下記のコードで考えます。
public class Main {
public static void main(String[] args) {
String weightText = "abc";
try {
int weight = Integer.parseInt(weightText);
System.out.println("体重:" + weight);
} catch (NumberFormatException e) {
System.out.println("数値を入力してください");
}
}
}3行目でweightTextは「abc」が入ります。
しかし「abc」は文字列なので6行目の「Integer.parseInt」の数値のに引っ掛かります。
この時にNumberFormatExceptionが入っているcatchが動作します。