以下のプログラムは、


int ikekka = 100/0;


で非チェック例外(java.lang.ArithmeticException)が発生する。


public class ExceptionSample1 {
public static void main(String args[]){
System.out.println("before");
int ikekka = 100/0;
System.out.println("end");
}
}


実行結果


before

Exception in thread "main" java.lang.ArithmeticException: / by zero
at book.ExceptionSample1.main(ExceptionSample1.java:6)

endが表示されていない。


非チェック例外は例外処理がされていないと、システム側がエラーメッセージを表示し強制的にプログラムの実行を停止する。



後、二つほど例。


【コーディング】

public class ExceptionSample1 {
public static void main(String args[]){
System.out.println("before");
hogeMethod();
System.out.println("end");
}

private static void hogeMethod(){
System.out.println("hogeMethod start.....");
int ikekka = 100/0;
System.out.println("hogeMethod end.....");
}
}


【結果】

before
hogeMethod start.....
Exception in thread "main" java.lang.ArithmeticException: / by zero
at book.ExceptionSample1.hogeMethod(ExceptionSample1.java:12)
at book.ExceptionSample1.main(ExceptionSample1.java:6)


【コーディング】

public class ExceptionSample1 {
public static void main(String args[]){
System.out.println("before");
HogeClass classHoge = new HogeClass();
classHoge.hogeMethod();
System.out.println("end");
}
}


public class HogeClass {
public static void hogeMethod(){
System.out.println("hogeMethod start.....");
int ikekka = 100/0;
System.out.println("hogeMethod end.....");
}
}


【結果】

before
hogeMethod start.....
Exception in thread "main" java.lang.ArithmeticException: / by zero
at book.HogeClass.hogeMethod(HogeClass.java:6)
at book.ExceptionSample1.main(ExceptionSample1.java:7)