Java

Exception re-throwing, try-catch문에서의 return

기초공사 2023. 5. 26. 19:00

예외를 양쪽에서 처리해야 할 경우 일부분만 처리하고 다시 예외를 throw 해서 사용하는 곳으로 예외를 떠기는 방식을 예외 되던지기 Exception re-throwing이라고 한다.

 

public class Test {
	public static void main(String[] args) {
		try {
			method();
		} catch (Exception e) {
			System.out.println("main(String[]) 예외가 처리됨");
		}
		
	}
	
	static void method() throws Exception {
		try {
			throw new Exception();
		} catch (Exception e) {
			System.out.println("method() 예외가 처리됨");
			throw e; // 예외 되던지기 
		}
	}
}

 

 

 

try-catch에서의 return 

public class Test {
	
	public static void main(String[] args) {
		int a = 10, b = 1;
		
		System.out.println(method(a, b));
	}
	
	static int method(int i, int j) {
		int result = 0;
		try {
			// b == 0 이면 ArithmeticException 발생
			System.out.println("try문 입니다.");
			result = i/j;
			System.out.println("다음 문장");
			return result;
		} catch (ArithmeticException e) {
			System.out.println("catch문 입니다.");
			return result;
		} finally {
			System.out.println("finally문 입니다.");
			System.out.println("method(int, int) 종료");
		}
	}
}

결과

b != 0일 때

더보기

try문 입니다.
다음 문장
finally문 입니다.
method(int, int) 종료
10

b == 0일때

더보기

try문 입니다.
catch문 입니다.
finally문 입니다.
method(int, int) 종료

 

b가 0이 아니라 ArithmeticException이 발생하지 않을 경우 try → finally → return 순으로 실행되며 b가 0이라 ArithmeticException이 발생하면 try(예외 발생 문장까지) → catch → finally → return 순으로 실행되는 것을 알 수 있다.