Minggu, 18 April 2010

Java eksepsi

class Eksepsi{

Eksepsi(){
/*konstruktor*/

}

public void eksepsiThrowStandar(int kode) throws Exception{
if(kode < 1){
Exception e = new Exception();
throw e;
}
}

public void eksepsiThrowSendiri(int kode) throws Exception{
if(kode < 1){
Exception e = new Exception("error");
throw e;
}
}

}

class CobaEksepsi{

public static void main(String[] args) {

Eksepsi eks = new Eksepsi();
int[] tabInt = new int[10];

System.out.println("eksepsi throw standar\n");
/*eksepsi throw standar*/
try{

eks.eksepsiThrowStandar(-1);

}
catch(Exception e){

e.printStackTrace();

}

System.out.println("\n-------------------------\n");

System.out.println("eksepsi throw sendiri\n");
/*eksepsi throw dengan kalimat sendiri*/
try{

eks.eksepsiThrowSendiri(-1);

}
catch(Exception e){

e.printStackTrace();

}

System.out.println("\n-------------------------\n");

System.out.println("eksepsi try catch\n");
/*eksepsi try catch karena mengakses indeks array lebih dari jumlah tempat array*/
try{

tabInt[10] = 10;

}
catch(Exception e){

e.printStackTrace();

}

System.out.println("\n-------------------------\n");

}

}