Java wirft Schlüsselwort
Beispiel
Lösen Sie eine Ausnahme aus, wenn das Alter unter 18 ist (geben Sie „Zugriff verweigert“ aus). Wenn das Alter 18 Jahre oder älter ist, drucken Sie „Zugang gewährt“ aus:
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...)
}
}
Definition und Verwendung
Das throws
Schlüsselwort gibt an, welcher Ausnahmetyp von einer Methode ausgelöst werden kann.
In Java sind viele Ausnahmetypen verfügbar: ArithmeticException
, ClassNotFoundException
, ArrayIndexOutOfBoundsException
, SecurityException
, usw.
Unterschiede zwischen throw
und 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:
|
Verwandte Seiten
Lesen Sie mehr über Ausnahmen in unserem Java Try..Catch Tutorial .