[Java] 예외 (2)

SeongEon Kim·2022년 5월 8일
0

JAVA

목록 보기
33/52
  1. 다양한 예외들
package org.opentutorials.javatutorials.exception;
 
class A{
    private int[] arr = new int[3];
    //배열 arr은 3개의 값을 담을 수 있다.
    A(){
        arr[0]=0;
        arr[1]=10;
        arr[2]=20;
    }
    public void z(int first, int second){
        System.out.println(arr[first] / arr[second]);
    }
}
 
public class ExceptionDemo1 {
    public static void main(String[] args) {
        A a = new A();
        a.z(10, 1);
        //하지만 10번째 인덱스를 호출하고 있다.
    }
}

위 코드는 아래와 같이 오류가 나온다.

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
    at org.opentutorials.javatutorials.exception.A.z(ExceptionDemo1.java:11)
    at org.opentutorials.javatutorials.exception.ExceptionDemo1.main(ExceptionDemo1.java:18)

오류가 나온 이유는 배열에 담긴 값이 3개인데, 10번째 값을 호출하고 있으므로 오류가 생기는 것이다.
즉, 존재하지 않는 값을 가져오려고 시도했으므로 ArrayIndexOutOfBoundsException 가 발생했다.

또 다른 코드를 확인해보자.

package org.opentutorials.javatutorials.exception;

class A{
   private int[] arr = new int[3];
   A(){
       arr[0]=0;
       arr[1]=10;
       arr[2]=20;
   }
   public void z(int first, int second){
       System.out.println(arr[first] / arr[second]);
   }
}

public class ExceptionDemo1 {
   public static void main(String[] args) {
       A a = new A();
       a.z(1, 0);
   }
}

위의 코드를 실행시킬 경우 결과는 아래와 같다.

Exception in thread "main" java.lang.ArithmeticException: / by zero
    at org.opentutorials.javatutorials.exception.A.z(ExceptionDemo1.java:11)
    at org.opentutorials.javatutorials.exception.ExceptionDemo1.main(ExceptionDemo1.java:18)

위의 오류는 10을 0으로 나누려고 했기 때문에 ArithmeticException을 발생시킨다.

더 긴 코드를 아래에서 확인해보자.

package org.opentutorials.javatutorials.exception;
 
class A{
    private int[] arr = new int[3];
    A(){
        arr[0]=0;
        arr[1]=10;
        arr[2]=20;
    }
    public void z(int first, int second){
        try {
            System.out.println(arr[first] / arr[second]);
        } catch(ArrayIndexOutOfBoundsException e){
            System.out.println("ArrayIndexOutOfBoundsException");
        } catch(ArithmeticException e){
            System.out.println("ArithmeticException");
        } catch(Exception e){
            System.out.println("Exception");
        }
         
    }
}
 
public class ExceptionDemo1 {
    public static void main(String[] args) {
        A a = new A();
        a.z(10, 0);
        a.z(1, 0);
        a.z(2, 1);
    }
}

위의 코드는 다중 catch를 보여준다. 조건문의 else if 처럼 여러 개의 catch를 하나의 try 구문에서 사용할 수 있다. 이를 통해 보다 간편하게 다양한 상황에 대응할 수 있다.
try 구문에서 예외가 발생했을 때 그 예외의 종류가 ArrayIndexOutOfBoundsException이라면 "ArrayIndexOutOfBoundsException"이 실행되고, ArithemeticException이라면 "ArithemeticException"이 실행되고 그 외의 것이라면 18행이 실행된다는 의미다.

만약 중간에 있는 메소드 z의 코드를 변경하면

public void z(int first, int second){
	try {
   	System.out.println(arr[first] / arr[secdond]);
   } catch(Exception e){
   	System.out.println("Exception);
   }
}

이 코드를 실행시키면 아래와 같이 나온다.

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
    Unreachable catch block for ArrayIndexOutOfBoundsException. It is already handled by the catch block for Exception
    Unreachable catch block for ArithmeticException. It is already handled by the catch block for Exception
 
    at org.opentutorials.javatutorials.exception.A.z(ExceptionDemo1.java:15)
    at org.opentutorials.javatutorials.exception.ExceptionDemo1.main(ExceptionDemo1.java:27)

그것은 Exception이 ArrayIndexOutOfBoundsException, ArithemeticException 보다 포괄적인 예외를 의미하기 때문에 Exception 이후에 등장하는 catch 문은 실행될 수 없는 구문이기 때문이다. 자바 컴파일러가 불필요한 로직을 감지하고 이를 개발자에게 알려주는 것이다.

profile
꿈을 이루는 사람

0개의 댓글