Java anahtar kelime atmak
Örnek
Yaş 18'in altındaysa bir istisna atın ("Erişim reddedildi" yazdırın). Yaş 18 veya daha büyükse, "Erişim izni verildi" ifadesini yazdırın:
public class Main {
static void checkAge(int age) {
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...)
}
}
Tanım ve Kullanım
Anahtar throw
kelime, özel bir hata oluşturmak için kullanılır.
İfade , bir istisna türüylethrow
birlikte kullanılır . Java'da birçok istisna türü mevcuttur: , , , , vb.ArithmeticException
ClassNotFoundException
ArrayIndexOutOfBoundsException
SecurityException
İstisna türü, genellikle yukarıdaki örnekte olduğu gibi özel bir yöntemle birlikte kullanılır.
throw
ve arasındaki farklar 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:
|
İlgili Sayfalar
Java Try..Catch Eğitimimizde istisnalar hakkında daha fazla bilgi edinin .