반응형
SMALL
package 생활코딩;
public class ExceptionApp {
public static void main(String[] args) {
System.out.println(1);
int [] scores = {10,20,30};
try {
System.out.println(scores[3]);
}catch (ArrayIndexOutOfBoundsException e){
System.out.println("잘못된 인덱스입니다.");
}
try {
System.out.println(2/0);
}catch (ArithmeticException e) {
System.out.println("잘못된 계산입니다.");
}
//--------------------------------------------------------//
try {
System.out.println(scores[1]);
System.out.println(scores[5]);
System.out.println(scores[0]);
System.out.println(2/0);
}catch (ArrayIndexOutOfBoundsException e){
System.out.println("잘못된 인덱스 입니다.");
}catch (ArithmeticException e){
System.out.println("잘못된 값입니다.");
}
System.out.println(3);
//-----------------------------------------------------------//
for (int a : scores) {
System.out.println(a);
}
}
}
1
잘못된 인덱스입니다.
잘못된 계산입니다.
-----------------------
20
잘못된 인덱스 입니다. -> 잘못된 인덱스를 반환하고 try 값 다 무시
3
------------------------
10
20
30
package 생활코딩;
public class ExceptionApp {
public static void main(String[] args) {
System.out.println(1);
int [] scores = {10,20,30};
try {
System.out.println(scores[1]);
System.out.println(scores[5]);
System.out.println(scores[0]);
System.out.println(2/0);
}
catch (Exception e){
System.out.println("오류가 발생했습니다.");
}
}
catch (ArrayIndexOutOfBoundsException e){
System.out.println("잘못된 인덱스 입니다.");
}catch (ArithmeticException e){
System.out.println("잘못된 값입니다.");
}
위 코드를
catch(Exception e){
System.out.println("~")
}
로 가능
Exception e -> 부모클래스이기 때문에 포괄적으로 처리 가능.(ArrayIndexOutOfBoundsException e, rithmeticException e...)
catch (Exception e){
System.out.println("오류가 발생했습니다. "+e.getMessage());
e.printStackTrace();
}
Exception e -> e 부분은 수정 가능.
e를 i 로 수정 시 i.getMessage()로 바꿈.
e.getMessage() : 에러의 원인을 간단하게 출력.
e.printStackTrace() : 에러의 발생근원지를 찾아서 단계별로 에러를 출력.
e.toString() : 에러의 Exception 내용과 원인을 출력
반응형
LIST
'JAVA > JAVA Note' 카테고리의 다른 글
다형성, 접근제어자, final, abstrack (0) | 2023.08.16 |
---|---|
interface, 다형성 (0) | 2023.08.16 |
try catch finally / try with resource statements (0) | 2023.08.16 |
indexOf, lastindexOf (0) | 2023.08.16 |
StringBuilder sb = new StringBuilder(); (0) | 2023.08.16 |