TIL/남궁성의 자바의 정석
자바의 정석 ch8-18 연결된 예외(chained exception)
minOE
2024. 9. 23. 12:40
728x90
연결된 예외(chained exception)
- 한 예외가 다른 에외를 발생시킬 수 있다.
- 예외 A가 예외 B를 발생시키면, A는 B의 원인 예외(cause exception)
Throwable initCause(Throwable cause) : 지정한 예외를 원인 예외로 등록
Throwable getCause() : 원인 예외 반환
// 원인 예외를 초기화하는 메서드 (한 번만 호출 가능) public synchronized Throwable initCause(Throwable cause) { if (this.cause != null) { throw new IllegalStateException("Can't overwrite cause"); } if (cause == this) { throw new IllegalArgumentException("Self-causation not permitted"); } this.cause = cause; return this; } // 원인 예외를 반환하는 메서드 public Throwable getCause() { return (cause == this ? null : cause); }
예시// SpaceException 정의 class SpaceException extends Exception { public SpaceException(String message) { super(message); } } // InstallException 정의 class InstallException extends Exception { public InstallException(String message, Throwable cause) { super(message, cause); } } public class Main { public static void main(String[] args) { try { // 원인 예외 SpaceException 발생 throw new SpaceException("디스크 공간이 부족합니다."); } catch (SpaceException e) { // SpaceException을 원인으로 InstallException 발생 throw new InstallException("설치 실패", e); } } }
출력결과Exception in thread "main" InstallException: 설치 실패 at Main.main(Main.java:16) Caused by: SpaceException: 디스크 공간이 부족합니다. at Main.main(Main.java:13)
연결된 예외 사용하는 이유
[이유1] 여러 예외를 하나로 묶어서 다루기 위해서
// 디스크 공간 부족 예외 class SpaceException extends Exception { public SpaceException(String message) { super(message); } } // 네트워크 오류 예외 class NetworkException extends Exception { public NetworkException(String message) { super(message); } } // 설치 관련 예외 class InstallException extends Exception { public InstallException(String message, Throwable cause) { super(message, cause); } } // 설치 클래스 public class Install { public void performInstallation() throws InstallException { try { // 디스크 공간 부족 예외 발생 throw new SpaceException("디스크 공간이 부족합니다."); } catch (SpaceException e) { // 첫 번째 예외를 원인으로 설치 예외 발생 InstallException installException = new InstallException("설치 실패", e); try { // 네트워크 오류 예외 발생 throw new NetworkException("네트워크 연결에 문제가 있습니다."); } catch (NetworkException e2) { // 두 번째 예외를 원인으로 연결 installException.initCause(e2); } throw installException; // 연결된 설치 예외 던짐 } } public static void main(String[] args) { Install install = new Install(); try { install.performInstallation(); } catch (InstallException e) { System.out.println("최종 예외: " + e.getMessage()); System.out.println("원인 예외: " + e.getCause().getMessage()); e.printStackTrace(); } } }
출력결과최종 예외: 설치 실패 원인 예외: 네트워크 연결에 문제가 있습니다. InstallException: 설치 실패 at Install.performInstallation(Install.java:12) Caused by: java.lang.NetworkException: 네트워크 연결에 문제가 있습니다. at Install.performInstallation(Install.java:20) Caused by: java.lang.SpaceException: 디스크 공간이 부족합니다. at Install.performInstallation(Install.java:5)
[이유2] checked 예외를 unchecked예외로 변경할떄// 디스크 공간 부족 예외 (Checked) class SpaceException extends Exception { public SpaceException(String message) { super(message); } } // 메모리 부족 예외 (Unchecked) class MemoryException extends RuntimeException { public MemoryException(String message) { super(message); } } // 설치 클래스 public class Installer { public void startInstall() throws SpaceException { // 디스크 공간 부족 예외 발생 throw new SpaceException("디스크 공간이 부족합니다."); // 메모리 부족 예외 발생 (Unchecked) // throw new MemoryException("메모리가 부족합니다."); } public static void main(String[] args) { Installer installer = new Installer(); try { installer.startInstall(); } catch (SpaceException e) { System.out.println("체크된 예외 발생: " + e.getMessage()); } // 메모리 부족 예외는 Unchecked 예외이므로 따로 처리하지 않아도 됩니다. throw new MemoryException("메모리가 부족합니다."); } }
체크된 예외 발생: 디스크 공간이 부족합니다. Exception in thread "main" MemoryException: 메모리가 부족합니다.
728x90