Java -worp Trefwoord
Voorbeeld
Geef een uitzondering als de leeftijd onder de 18 is (print "Toegang geweigerd"). Als de leeftijd 18 jaar of ouder is, druk dan "Toegang verleend" af:
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...)
}
}
Definitie en gebruik
Het throw
trefwoord wordt gebruikt om een aangepaste fout te maken.
De throw
instructie wordt gebruikt in combinatie met een uitzonderingstype . Er zijn veel soorten uitzonderingen beschikbaar in Java: ArithmeticException
, ClassNotFoundException
, ArrayIndexOutOfBoundsException
, SecurityException
, etc.
Het uitzonderingstype wordt vaak gebruikt in combinatie met een aangepaste methode , zoals in het bovenstaande voorbeeld.
Verschillen tussen throw
en 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:
|
Gerelateerde pagina's
Lees meer over uitzonderingen in onze Java Try..Catch Tutorial .