예외를 양쪽에서 처리해야 할 경우 일부분만 처리하고 다시 예외를 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) 종료 
0 
b가 0이 아니라 ArithmeticException이 발생하지 않을 경우 try → finally → return 순으로 실행되며 b가 0이라 ArithmeticException이 발생하면 try(예외 발생 문장까지) → catch → finally → return 순으로 실행되는 것을 알 수 있다.
'Java' 카테고리의 다른 글
| Object class의 메서드 (0) | 2023.05.30 | 
|---|---|
| Chained Exception (0) | 2023.05.29 | 
| 사용자 정의 예외 (0) | 2023.05.24 | 
| throw, checked - unchecked 예외, throw (0) | 2023.05.23 | 
| 예외 (0) | 2023.05.22 |