LoginSignup
3
4

More than 5 years have passed since last update.

初めてのtry~catch

Last updated at Posted at 2017-05-15

public class Test {
    public static void main(String[] args){
    Scanner in = new Scanner(System.in);
    int in_next = in.nextInt();
    System.out.println(in_next + "は無事通ったよ");
    in.close();
    }
}

上のような物を作り実行します。
コンソールに"ああ"などを入れて、入力するとエラーが起こります。
これにtry~catchを組み込むとどうなるか。


public class Test {
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        try{
            int in_next = in.nextInt(); 
            System.out.println(in_next + "は無事通ったよ");
            in.close();
        }
        catch(Exception e){
            System.out.println("エラーだよ"); 
            System.out.println(e);
        }
    }
}

図のようにしました。
まず、try文の中のことに挑戦をします。
そこで何らかのエラーが起こったらcatchに移行します。
スローされるとか言いますね。
catchの中にあるExceptionは例外という意味で、これは例外クラスです。
隣のeの中に例外内容が入ります。
実行して適当な文字を入れてみましょう。
エラー内容がコンソールにでましたね。
自分はjava.util.InputMismatchExceptionというのが出たので、同じエラーを
起こしたときにだけにcatchするように絞ってみる。


import java.util.InputMismatchException;
import java.util.Scanner;
public class Test {
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        try{
            int in_next = in.nextInt();
            System.out.println(in_next + "は無事通ったよ");
            in.close();
        }
        catch(InputMismatchException e){
            System.out.println("エラーだよ");
            System.out.println(e);
        }
    }
}

catchは増やしてもよい。もう一個catchを書いても問題ない。
エラー別でメッセージを出しても良いだろう。

3
4
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4