Archive for the ‘exception’ Tag

Membuat Java Exception Sendiri

Langsung saja. Kita dapat membuat exception sendiri, dengan menurunkan kelas Exception milik Java. Ingat bahwa ada 2 macam exception, ada JVM, dan programmatic. Berikut adalah contohnya :

class MyException extends Exception{

	public MyException(String message){
		super(message);
	}

}

public class ExceptionTest{
	public void selectFood(String food) throws MyException{
		if(food.equals("sate")){
			throw new MyException("you choose wrong food");
		}
	}

	public static void main(String[] ar){
		ExceptionTest et = new ExceptionTest();
		try{
			et.selectFood("sate");
		}catch(MyException e){
			System.out.println(e.getMessage());
		}

		System.out.println(et);
	}
}

Pada kode di atas, kita memiliki kelas MyException yang merupakan sub-class dari Exception. Fungsi class di atas, ketika user memberikan input kata ’sate’ maka program akan melemparkan exception.

Have Fun !!!