Exception Handling
public class Test02 {
public static void main(String[] args) {
int []arr=new int[4];
for(int i=0; i<4 ;i++){
arr[i]=i+1;
}
for(int i=0; i<5 ;i++){
try{
System.out.println(arr[i]); // for문이 배열 인덱스를 넘었으므로 예외가 발생할 가능성이 있는 코드
}catch(ArrayIndexOutOfBoundsException ae){ // 예외를 처리하는 코드
System.out.println("배열 넘었어");
}
}
System.out.println("End");
}
}
다중 예외처리
public class Test02 {
public static void main(String[] args) {
int []arr=new int[4];
for(int i=0; i<4 ;i++){
arr[i]=i+1;
}
for(int i=0; i<5 ;i++){
try{
System.out.println(arr[i]);
int data=arr[i]/0;
}catch(ArrayIndexOutOfBoundsException ae){
System.out.println("배열 넘었어");
}catch(ArithmeticException ar){
System.out.println("0으로 나누지마");
}
}
System.out.println("End");
}
}
public class Test02 {
public static void main(String[] args) {
int[] arr = new int[4];
for (int i = 0; i < 4; i++) {
arr[i] = i + 1;
}
for (int i = 0; i < 5; i++) {
try {
System.out.println(arr[i]);
int data = arr[i] / 0;
} catch (ArrayIndexOutOfBoundsException ae) {
System.out.println("배열 넘었어");
} catch (ArithmeticException ar) {
System.out.println("0으로 나누지마");
}catch(Exception e){ // 예상 못할 코드를 부모의 것으로 방지 , dynamic binding
System.out.println("error");
}
}
System.out.println("End");
}
}
public class Test02 {
public static void main(String[] args) {
int[] arr = new int[4];
for (int i = 0; i < 4; i++) {
arr[i] = i + 1;
}
for (int i = 0; i < 5; i++) {
try {
System.out.println(arr[i]);
} catch (ArrayIndexOutOfBoundsException ae) {
System.out.println("배열 넘었어");
return;
} finally {
System.out.println("End"); //앞의 return 때문에 출력이 안됨
/* but, fianlly를 쓰면 예외발생여부와 상관없이 무조건 실행
finally 블럭 : 예외가 발생하던 발생하지 않던 꼭 실행을 하겠다! return을 만나더라도 finally 블럭을 다 실행하고 끝을 냄.
*/
}
}
}
}