Java 가 키워드 를 던졌습니다 .
예시
연령 이 18세 미만인 경우 예외를 throw합니다 ("액세스 거부됨" 인쇄). 연령이 18세 이상인 경우 "접근 허가됨"을 인쇄하십시오.
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...)
}
}
정의 및 사용
키워드 는 throws
메서드에서 throw될 수 있는 예외 유형을 나타냅니다.
ArithmeticException
Java 에는 , ClassNotFoundException
, ArrayIndexOutOfBoundsException
, SecurityException
등 많은 예외 유형이 있습니다 .
throw
와 의 차이점 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:
|
관련 페이지
Java Try..Catch Tutorial 에서 예외에 대해 자세히 읽어보십시오 .