Java melempar Kata Kunci
Contoh
Berikan pengecualian jika usia di bawah 18 (cetak "Akses ditolak"). Jika usia 18 tahun atau lebih, cetak "Akses diberikan":
public class Main {
static void checkAge(int age) throws ArithmeticException {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
}
else {
System.out.println("Access granted - You are old enough!");
}
}
public static void main(String[] args) {
checkAge(15); // Set age to 15 (which is below 18...)
}
}
Definisi dan Penggunaan
Kata throws
kunci menunjukkan jenis pengecualian apa yang mungkin dilemparkan oleh suatu metode.
Ada banyak tipe exception yang tersedia di Java: ArithmeticException
, ClassNotFoundException
, ArrayIndexOutOfBoundsException
, SecurityException
, dll.
Perbedaan antara throw
dan throws
:
throw | throws |
---|---|
Used to throw an exception for a method | Used to indicate what exception type may be thrown by a method |
Cannot throw multiple exceptions | Can declare multiple exceptions |
Syntax:
|
Syntax:
|
Halaman Terkait
Baca lebih lanjut tentang pengecualian di Java Try..Catch Tutorial kami .