Example การใช้ Exception พื้นฐานดักจับทุกชนิดของ Error
package com.java.myapp;
public class MyClass {
public static void main(String[] args) {
try {
int x = 200 ;
int y = 0 ;
int z = x / y;
System.out.println(" x / y = " + z) ;
} catch(Exception e) {
System.out.println("Error : " + e.getMessage());
}
}
}
Example การใช้ Exception สร้างเงื่อนไขของชนิด Error
package com.java.myapp;
public class MyClass {
public static void main(String[] args) {
try {
int x = 200 ;
int y = 0 ;
int z = x / y;
System.out.println(" x / y = " + z) ;
} catch(ArithmeticException e) {
System.out.println("Number Incorrect.");
} catch(Exception e) {
System.out.println("Error Others.");
}
}
}
java.io.FileNotFoundException: C:\java\thaicreate.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)
at com.java.myapp.MyClass.main(MyClass.java:18)