gakkie プログラミング 備忘録

tech::expert(現tech camp) 45期

Java 例外処理

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        System.out.println("ようこそ\n数字を入力してください");
        String s = new Scanner(System.in).nextLine();
        //i = Integer.parseInt(s);
        //System.out.println("入力値:" + s);
        try {
            //例外が発生する可能性のある処理
            int i = Integer.parseInt(s);
            System.out.println(i);
        } catch (NumberFormatException e) {
            //例外が発生した場合の処理(例外が発生しなければ行われない処理)
            System.out.println("ちゃんと数字を入力してください!");
        }
    }
}