Java lança palavra- chave
Exemplo
Lance uma exceção se a idade for inferior a 18 anos (imprima "Acesso negado"). Se a idade for maior de 18 anos, imprima "Acesso 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...)
}
}
Definição e uso
A palavra- throws
chave indica qual tipo de exceção pode ser lançada por um método.
Existem muitos tipos de exceção disponíveis em Java: ArithmeticException
, ClassNotFoundException
, ArrayIndexOutOfBoundsException
, SecurityException
, etc.
Diferenças entre throw
e 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
Leia mais sobre exceções em nosso Java Try..Catch Tutorial .