Page 64 - e-modul pbo
P. 64
Contoh listing program penggunaan Throws :
class G
public class G
{
public static void main(String[] args) {
try {
f();
}
catch(Exception e){
System.out.println(e);
}
}
public static void f()throws NullPointerException,
ArrayIndexOutOfBoundsException{
//implementasi method
throw new NullPointerException();
//throw new ArrayIndexOutOfBoundsException();
}
}
output
java.lang.NullPointerException
Contoh listing program lainnya :
public class H
{
public static void main(String[] args) {
try
{
f();
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void f()throws NullPointerException,
ArrayIndexOutOfBoundsException
{
//implementasi method
//throw new NullPointerException();
throw new ArrayIndexOutOfBoundsException();
}
}
Output program diatas :
java.lang.ArrayIndexOutOfBoundsException
Kedua program diatas merupakan pengguaan keywordthrows pada method. Ketika
method tersebut dipanggil dalam blocktry. Maka method tersebut akan membuat object
yang merupakan subclass dari classThrowable dan method tersebut akan melemparkan
Pemrograman Berorientasi Objek Kelas XI – Semester 2 59