[Java] 15. 예외 처리

김주희's avatar
Feb 26, 2025
[Java] 15. 예외 처리
수정필요

1. try - catch

package ex15; public class Run01 { public static int gcd(int a, int b) { //if (b == 0) return a; try { return gcd(b, a % b); } catch (ArithmeticException e) { return a; } } public static void main(String[] args) { int r = gcd(10, 20); // [1,2,5,10], [1,2,4,5,10,20] System.out.println(r); } }
 
 

2. RuntimeException VS CheckedException

notion image

1. RuntimeException

package ex15; public class DivideByZeroOK { public static void main(String[] args) { try { int result = 10 / 0; System.out.println(result); } catch (ArithmeticException e) { System.out.println("괜찮아 : " + e.getMessage()); e.printStackTrace(); // 디폴트 } } }
 

2. CheckedException

package ex15; public class Check01 { public static void main(String[] args) { System.out.println("시작"); try { Thread.sleep(5000); //5초 } catch (InterruptedException e) { System.out.println("도중에 꺼졌는데 괜찮아."); } System.out.println("끝"); } }
package ex15; import java.io.FileNotFoundException; import java.io.FileReader; public class Check02 { public static void main(String[] args) { try { FileReader file = new FileReader("C:/hello/good.txt"); } catch (FileNotFoundException e) { System.out.println("파일을 내가 직접 C:/hello/good.txt 생성"); } } }
 

4. 예외 처리

notion image

1. 강제로 예외를 터트리는 방법 (강제로 Exception)

package ex15; public class Try01 { public static void main(String[] args) { throw new ArithmeticException("강제로 만든 Exception"); } }

2. 예외를 위임하는 방법 (호출한 쪽에서 Exception 한번에 해결 가능)

package ex15; class A { static int start(boolean check) { int r = B.m1(check); return r; } } class B { static int m1(boolean check) { if (check) { return 1; } else { throw new RuntimeException("false 오류남"); } } } public class Try02 { public static void main(String[] args) { try { int r = A.start(false); System.out.println("정상 : " + r); } catch (Exception e) { System.out.println("오류 처리 방법 : " + e.getMessage()); } } }
 

5. 로그인 예제

1. 정상/ 비정상 둘 다 return으로 해결(X) → 정상만 return해야 된다!

package ex15; class Repository { // 1이면 존재하는 회원, -1이면 존재하지 않음 int findIdAndPw(String id, String pw) { System.out.println("레포지토리 findIdAndPw 호출됨"); if (id.equals("ssar") && pw.equals("5678")) { return 1; } else { return -1; } } } // 책임 : 유효성 검사 class Controller { String login(String id, String pw) { System.out.println("컨트롤러 로그인 호출됨"); if (id.length() < 4) { return "유효성검사 : id의 길이가 4자 이상이어야 합니다."; } if (pw.length() < 4) { return "유효성검사 : id의 길이가 4자 이상이어야 합니다."; } Repository repo = new Repository(); int code = repo.findIdAndPw(id, pw); if (code == -1) { return "id 혹은 pw가 잘못됐습니다"; } return "로그인이 완료되었습니다"; } } public class Try03 { public static void main(String[] args) { Controller con = new Controller(); String message = con.login("ssar", "123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789"); System.out.println(message); } }
 

2. 위임으로 해결

package ex15; class Repository { // 1이면 존재하는 회원, -1이면 존재하지 않음 void findIdAndPw(String id, String pw) { System.out.println("레포지토리 findIdAndPw 호출됨"); if (!(id.equals("ssar") && pw.equals("5678"))) { throw new RuntimeException("아이디 혹은 비번 틀림"); } } } // 책임 : 유효성 검사 class Controller { void login(String id, String pw) { System.out.println("컨트롤러 로그인 호출됨"); if (id.length() < 4) { throw new RuntimeException("id 길이가 최소 4자 이상이어야 해요"); } if (pw.length() < 4) { throw new RuntimeException("pw 길이가 최소 4자 이상이어야 해요"); } Repository repo = new Repository(); repo.findIdAndPw(id, pw); } } public class Try03 { public static void main(String[] args) { Controller con = new Controller(); try { con.login("ssar", "123"); } catch (Exception e) { System.out.println(e.getMessage()); } } }
Share article

jay0628