Słowo kluczowe rzutu Java
Przykład
Zrzuć wyjątek, jeśli masz mniej niż 18 lat (drukuj „Odmowa dostępu”). Jeśli masz ukończone 18 lat, wydrukuj „Przyznano dostęp”:
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...)
}
}
Definicja i użycie
Słowo throw
kluczowe służy do tworzenia niestandardowego błędu.
Instrukcja throw
jest używana razem z typem wyjątku . W Javie dostępnych jest wiele typów wyjątków: ArithmeticException
, ClassNotFoundException
, ArrayIndexOutOfBoundsException
, SecurityException
, itd.
Typ wyjątku jest często używany razem z metodą niestandardową , jak w powyższym przykładzie.
Różnice między throw
a 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:
|
Powiązane strony
Przeczytaj więcej o wyjątkach w naszym samouczku Java Try..Catch .