Java melempar Kata Kunci

Kata Kunci Jawa


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 throwskunci 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 throwdan 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:
  • throw is followed by an object (new type)
  • used inside the method
Syntax:
  • throws is followed by a class
  • and used with the method signature

Halaman Terkait

Baca lebih lanjut tentang pengecualian di Java Try..Catch Tutorial kami .


Kata Kunci Jawa