Pertemuan 30 September 2014
Contoh Try-Catch (DemoEksepsi.java)
public class DemoEksepsi { public static void main(String[] args) { //int d1 = 0; //int a1 = 42/d1; try{ int d = 0; System.out.println("Hello"); int[] arr = {1}; System.out.print(arr[22]); int a = 42/d; System.out.println("Berhasil"); } catch(ArithmeticException e){ System.out.println("Pembagian dengan Nol"); }catch(ArrayIndexOutOfBoundsException e){ System.out.println("Indeks melebihi jum elemen"); } catch(Exception e){ System.out.println("Eksepsi"); } } }
Contoh Throw-Throws
(DemoThrow.java)
import java.sql.SQLException; public class DemoThrow { public void metThrow() throws SQLException,IllegalAccessException{ int d = 1; if(d==0){ throw new SQLException(); }else if(d==1){ throw new IllegalAccessException(); }else{ int a = 42/d; } } }
(MainThrow.java)
import java.sql.SQLException; public class MainThrow { public static void main(String[] args) { DemoThrow d = new DemoThrow(); try{ d.metThrow(); }catch(SQLException e){ System.out.println("SQL Eksepsi di method methrow"); }catch(IllegalAccessException e){ System.out.println("Illegal Eksepsi di method methrow"); } } }