자바 throw 키워드
예시
연령 이 18세 미만인 경우 예외를 throw합니다 ("액세스 거부됨" 인쇄). 연령이 18세 이상인 경우 "접근 허가됨"을 인쇄하십시오.
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...)
}
}
정의 및 사용
키워드 는 throw
사용자 지정 오류를 만드는 데 사용됩니다.
문 은 예외 유형throw
과 함께 사용됩니다 . Java 에는 , , , 등 많은 예외 유형이 있습니다 .ArithmeticException
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 에서 예외에 대해 자세히 읽어보십시오 .