LoginSignup
0
0

More than 3 years have passed since last update.

try-catch-finally 例外処理 使い方 java

Last updated at Posted at 2020-09-19

環境:Windows10, Eclipse, java8

javaにおけるtry catch finallyを使った例外処理について記述します。

例外処理の書き方


try{
  処理
}catch(例外の型 引数){
  例外発生時の処理
}finally{
  最後に実行される処理(例外の有無関係なし)
}

使用例

    public static void main(String[] args) {
        double a = 99999;

        //----------例外処理が発生するケース----------
        System.out.println("-----例外発生-----");
        try {
            a = 30/0;
        }catch(ArithmeticException e) {
            System.out.println("例外処理:0では割れません");
            System.out.println(e);
        }finally {
            System.out.println("finally  "+ "a="+a);
        }

        //----------例外処理が発生しないケース----------
        System.out.println("-----正常-----");
        try {
            a = 30/3;
        }catch(ArithmeticException e) {
            System.out.println("例外処理:0では割れません");
            System.out.println(e);
        }finally {
            System.out.println("finally  "+ "a="+a);
        }
    }
実行結果
-----例外発生-----
例外処理:0では割れません
java.lang.ArithmeticException: / by zero
finally  a=99999.0
-----正常-----
finally  a=10.0

解説

以上のプログラムでは、a=30/0;の行にて、
ゼロで除算をしているため(解なしになってしまう)、例外(ArithmeticException)が発生しています。
そのため、以下の処理が実行されます。

        }catch(ArithmeticException e) {
            System.out.println("例外処理:0では割れません");
        }

そのため、実行結果として、「例外処理:0では割れません」と表示されました。

catch(例外の型 引数)について

catchの中身はどのように書けばよいのか。

上記での例
}catch(ArithmeticException e){

上記の例での、ArithmeticExceptionというのは、ゼロで除算すると投げられてくる例外です。

他の例外も、以下の形で書けますので、解説していきます。

}catch(例外の型 引数){

例外の型(例:ArithmeticException)

例外が発生した際に投げられてくる型を書く。

try内に書く処理に対応した例外処理を、リファレンスで調べて使う。
java11の場合:https://docs.oracle.com/javase/jp/11/docs/api/index-files/index-1.html

importを伴う場合

また、ファイル入出力操作等で例外処理をしたい場合に、
IOExceptionという例外を使う場合は

import java.io.IOException;

でパッケージをインポートする必要があることもあります。

今回のArithmeticExceptionという例外についても、

import java.lang.ArithmeticException

と記述してimportの必要がありそうです。
しかし、java.langはコンパイラ内で暗黙的にimportされるため、記述の必要はありません。
ちなみにSystem.out.printlnがimportなしで使えるのもこのためです。

引数(例:e)

命名は自由だが。「e」が使われることが多い。

今回の例では
「System.out.println(e);」を記述しているため、
実行結果に「java.lang.ArithmeticException: / by zero」
と表示され、例外を受け取っていることが確認できる。

0
0
0

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
0
0