High Fashioners Issue # 2 | Page 216

J. E. N. I.
2.4 Melempar Exception
2.4.1 Keyword Throw
Disamping menangkap exception, Java juga mengijinkan seorang user untuk melempar sebuah exception. Sintax pelemparan exception cukup sederhana.
throw < exception object >;
Perhatikan contoh berikut ini.
/* Melempar exception jika terjadi kesalahan input */ class ThrowDemo { public static void main( String args []){ String input =“ invalid input”; try { if( input. equals(“ invalid input”)) { throw new RuntimeException(" throw demo ");
} else {
System. out. println( input);
} System. out. println(" After throwing "); } catch( RuntimeException e) { System. out. println(" Exception caught here."); System. out. println( e);
}
}
}
2.4.2 Keyword Throws
Jika sebuah method dapat menyebabkan sebuah exception namun tidak menangkapnya, maka digunakan keyword throws. Aturan ini hanya berlaku pada checked exception. Anda akan mempelajari lebih lanjut tentang checked exception dan unchecked exception pada bagian selanjutnya,“ Kategori Exception”.
Berikut ini penulisan syntax menggunakan keyword throws:
< type > < methodName >(< parameterList >) throws < exceptionList > { < methodBody >
}
Sebuah method perlu untuk menangkap ataupun mendaftar seluruh exceptions yang mungkin terjadi, namun hal itu dapat menghilangkan tipe Error, RuntimeException, ataupun subclass-nya.
Pengenalan Pemrograman 2 7