Java 예외 - Try...Catch
자바 예외
Java 코드를 실행할 때 프로그래머의 코딩 오류, 잘못된 입력으로 인한 오류 또는 기타 예측할 수 없는 다른 오류가 발생할 수 있습니다.
오류가 발생하면 Java는 일반적으로 중지되고 오류 메시지를 생성합니다. 이에 대한 기술 용어는 Java에서 예외 가 발생 합니다(오류 발생).
자바 시도 및 잡기
명령문을 사용하면 실행 되는 try
동안 오류를 테스트할 코드 블록을 정의할 수 있습니다.
이 catch
명령문을 사용하면 try 블록에서 오류가 발생할 경우 실행할 코드 블록을 정의할 수 있습니다.
try
및 키워드 는 catch
쌍으로 제공됩니다.
통사론
try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}
다음 예를 고려하십시오.
myNumbers[10] 이(가) 존재하지 않기 때문에 오류가 발생 합니다.
public class Main {
public static void main(String[ ] args) {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]); // error!
}
}
출력은 다음과 같습니다.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
at Main.main(Main.java:4)
오류가 발생하면 를 사용 try...catch
하여 오류를 포착하고 일부 코드를 실행하여 처리할 수 있습니다.
예시
public class Main {
public static void main(String[ ] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}
}
출력은 다음과 같습니다.
Something went wrong.
드디어
이 명령문을 사용하면 결과에 관계없이 finally
뒤에 코드를 실행할 수 있습니다.try...catch
예시
public class Main {
public static void main(String[] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
} finally {
System.out.println("The 'try catch' is finished.");
}
}
}
출력은 다음과 같습니다.
Something went wrong.
The 'try catch' is finished.
던지기 키워드
throw
명령문을 사용하면 사용자 지정 오류를 생성할 수 있습니다 .
문 은 예외 유형throw
과 함께 사용됩니다 . Java 에는 ,
, , 등 많은 예외 유형이 있습니다 .ArithmeticException
FileNotFoundException
ArrayIndexOutOfBoundsException
SecurityException
예시
연령 이 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...)
}
}
출력은 다음과 같습니다.
Exception in thread "main" java.lang.ArithmeticException: Access denied - You must be at least 18 years old.
at Main.checkAge(Main.java:4)
at Main.main(Main.java:12)
나이 가 20 세인 경우 예외가 발생 하지 않습니다 .
예시
checkAge(20);
출력은 다음과 같습니다.
Access granted - You are old enough!