class ExException1{ public static void main (String[] args) { int x = 10/0; //0で除算 } }
【例2】任意の例外処理を行った例です。
class ExException2{ public static void main (String[] args) { try { int x = 10/0; //(1)0で除算 //例外ハンドラ } catch (ArithmeticException e) { //(2) System.out.println("0で除算はできません。"); } } }
【解説2】
import java.io.*; class ExException3 { public static void main (String[] args) { //チェック例外IOExceptionが発生する可能性がある処理 FileWriter exFile = new FileWriter("exFile.txt"); } }
【例4】チェック例外に対して、任意の例外処理を記載した時の例です。
import java.io.*; class ExException4 { public static void main (String[] args) { //任意の例外処理を記載 try { FileWriter exFile = new FileWriter("exFile.txt"); } catch(IOException e) { System.err.println(e.getMessage()); } } }