Variasi Exception

Mungkin rada basi, tapi mudah-mudahan bisa sharing sedikit. Salah satu syntax JAVA yang sering dipake try-catch beserta exception. Nah, karena kebiasaan pake IDE eclipse, kalo masuk exception, pasti pake e.printStackTrace(). Pas ujian sertifikasi, paling sering soal exception muncul saya gambarin dalam beberapa skenario :

Skenario 1

Throw exception dan catcher menggunakan super class nya.

public class SampleMain {
 
	public void sampleException() {
		throw new RuntimeException("runtime");
	}
 
	public void sampleNumberException() {
		throw new NumberFormatException("number format");
	}
 
	public static void main(String args[]) {
		try {
			SampleMain sm = new SampleMain();
			sm.sampleException();
			sm.sampleNumberException();
		} catch (/* skenario 1 */ Exception e) {
			System.out.println(e);
		}
	}
}

Output

java.lang.RuntimeException: runtime

Skenario 2

Throw exception dan catcher menggunakan expception yang berbeda.

public class SampleMain {
 
	public void sampleException() {
		throw new RuntimeException("runtime");
	}
 
	public void sampleNumberException() {
		throw new NumberFormatException("number format");
	}
 
	public static void main(String args[]) {
		try {
			SampleMain sm = new SampleMain();
			sm.sampleException();
			sm.sampleNumberException();
		} catch (/* skenario 2 */ NumberFormatException e) {
			System.out.println(e);
		}
	}
}

Output

Exception in thread "main" java.lang.RuntimeException: runtime
	at SampleMain.sampleException(SampleMain.java:4)
	at SampleMain.main(SampleMain.java:14)

CMIIW :).

Marifnst, 2014-07-16

Leave a Reply

Your email address will not be published. Required fields are marked *

Afiseaza emoticoanele Locco.Ro