Welcome to Abdul Malik Ikhsan's Blog

Custom Exception di Java

Posted in Tutorial Java by samsonasik on April 29, 2009

Bosan dengan nama Exception yang itu-itu aja (padahal mah, karena yang diketahui emang itu-itu aja, xi..xi..xi..), kita bisa lho, membuat custom exception sendiri, dengan blok penanganan error sendiri, caranya dengan menurunkan kelas Exception. contoh :

/**
 *
 * @author samsonasik
 */
public class SalahTulisException  extends Exception{   
    private String eksepsi;

    public SalahTulisException() {
        super();
        this.eksepsi = "";
    }

    public SalahTulisException(String e) {
        super();
        this.eksepsi = e;
    }

    @Override
    public String getMessage() {
        return this.eksepsi;
    }

}

Nah, sekarang kita coba test:

/**
*
* @author samsonasik
*/

public class Main {

//method validasi
public void validateNama(String n) throws SalahTulisException {
if (n.equals("samsonasik")) {
System.out.println("ganteng");
} else {
throw new SalahTulisException("salah tulis nama");
}
}

public static void main(String args[]){

Main m = new Main();
try {
m.validateNama("boys");
} catch(SalahTulisException e) {
System.out.println(e.getMessage());
}

}

}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: