「Java8」クラスNumberFormatExceptionをスローするサンプル
環境
Java8
Eclipse 2019
書式
public class NumberFormatException
extends IllegalArgumentException
アプリケーションが文字列を数値型に変換しようとしたとき、文字列の形式が正しくない場合にスローされます。
構文
try {処理コード}catch (NumberFormatException e) {メッセージ}
使用例
package com.arkgame.study;
public class ParseIntDemo {
      public static void main(String[] args) {
            String strA = "789";
            int re = Integer.parseInt(strA);
            System.out.println("文字列を数値型に変換する結果: " + re);
            
            System.out.println("\nNumberFormatExceptionのサンプル");
            String strB = "";
            try {
                  int re2 = Integer.parseInt(strB);
                  System.out.println(re2);
            } catch (NumberFormatException e) {
                  System.out.println("文字列strBは数値でではありません");
            }
      }
}
実行結果
文字列を数値型に変換する結果: 789 NumberFormatExceptionのサンプル 文字列strBは数値でではありません