[Java] Exception(throws, throw 예외처리 방법)

Hee·2024년 4월 2일

Java 복습

목록 보기
33/46
post-thumbnail

throws

예외가 발생했을 때 예외를 호출한 쪽에서 처리하도록 던져준다.

// 정수를 매개변수로 2개를 받아들인 후 나눗셈을 한 후 그 결과를 반환하는 divide 메소드정의, main 메소드에서는 divide 메소드를 호출

public class ExceptionExam2{
	public static void main(String[] args){
    	int i = 10;
        int j = 0;
        int k = divide(i, j);
        System.out.println(k);
    }
    
    public static int divide(int i, int j){
    	int k = i / j;
        return k;
    }
}

throws 포함하게끔 수정 후

// 메소드를 호출한 쪽에서 예외 처리하도록 divide 메소드 throws로 수정

public class ExceptionExam2{
	public static void main(String[] args){
    	int i = 10;
        int j = 0;
        int k = divide(i, j);
        System.out.println(k);
    }
    
    public static int divide(int i, int j) throws ArithmeticException{
    	int k = i / j;
        return k;
    }
}
  • 메소드 선언 뒤에 throws ArithmeticException이 적혀있는 것을 알 수 있다.
  • divide 메소드는 ArithmeticException이 발생하니 divide 메소드를 호출하는 쪽에서 오류를 처리하라는 뜻이다.

try-catch 구문 포함하게끔 수정 후

// divide 메소드를 호출한 쪽에서 예외처리 할 수 있도록 try-catch 문 추가

public class ExceptionExam2{
	public static void main(String[] args){
    	int i = 10;
        int j = 0;
        try{
          int k = divide(i, j);
          System.out.println(k);
        }catch(ArithmeticException e){
        	System.out.println("0으로 나눌 수 없음");
        }
    }
    
    public static int divide(int i, int j) throws ArithmeticException{
    	int k = i / j;
        return k;
    }
}


throw

throw는 오류를 떠넘기는 throws와 보통 같이 사용된다.

public class ExceptionExam3{
	public static void main(String[] args){
    	int i = 10;
        int j = 0;
        int k = divide(i, j);
        System.out.println(k);
    }
    
    public static int divide(int i, int j) throws IllegalArgumentException{
    	if(j == 0){
        	// 새로운 Exception 객체를 통해 오류 발생시키기
        	throw new IllegalArgumentException("0으로 나눌 수 없어요");
        }
    	int k = i / j;
        return k;
    }
}
  • 실행결과(에러발생)
    Exception in thread "main" java.lang.IllegalArgumentException: 0으로 나눌 수 없어요.
    at first/first.HelloWorld.divide(HelloWorld.java:13)
    at first/first.HelloWorld.main(HelloWorld.java:7)

  • j가 0일 경우에 new 연산자를 통해 IllegalArgumentException 객체가 만들어진다.

  • new 앞에 throw는 해당 라인에서 익셉션이 발생한다는 의미이다.

  • 즉 그 줄에서 오류가 발생했다는 것이다. 0으로 나눌 수 없습니다. 라는 오류가 발생한 것이다.

  • Exception 클래스 이름을 보면 Argument가 잘못되었기 때문에 발생한 오류라는 것을 알 수 있다.


에러도 발생하지 않고, 올바르지 않은 결과를 리턴하지 않도록 수정

public class ExceptionExam3{
	public static void main(String[] args){
    	int i = 10;
        int j = 0;
        try{
            int k = divide(i, j);
            System.out.println(k);
        }catch(IllegalArgumentException e){
        	System.out.println("0으로 나누면 안 됨");
        }
    }
    
    public static int divide(int i, int j) throws IllegalArgumentException{
    	if(j == 0){
        	throw new IllegalArgumentException("0으로 나눌 수 없어요");
        }
    	int k = i / j;
        return k;
    }
}
  • 출력결과(오류 발생하지 않음)
    0으로 나누면 안 됨
  • divide 메소드 뒤에 throws IllegalArgumentException은 해당 오류는 devide를 호출한 쪽에서 처리를 해야 한다는 것을 의미한다.
  • 호출한 부분의 try-catch 문을 통해 오류가 발생하지 않고, catch 블록의 문장이 실행되는 것을 알 수 있다.

0개의 댓글