Java lanza una palabra clave
Ejemplo
Lanza una excepción si la edad es menor de 18 años (imprime "Acceso denegado"). Si la edad es mayor de 18 años, escriba "Acceso concedido":
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...)
}
}
Definición y uso
La throws
palabra clave indica qué tipo de excepción puede lanzar un método.
Hay muchos tipos de excepciones disponibles en Java: ArithmeticException
, ClassNotFoundException
, ArrayIndexOutOfBoundsException
, SecurityException
, etc.
Diferencias entre throw
y 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:
|
páginas relacionadas
Obtenga más información sobre las excepciones en nuestro Tutorial de Java Try..Catch .