[자바 예외처리] 68. 예외처리 실습

김건우's avatar
Feb 17, 2025
[자바 예외처리] 68. 예외처리 실습

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 Controller01 { 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) { Controller01 con = new Controller01(); String message = con.login("ssar", "123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789"); System.out.println(message); } }
정상은 리턴을 해도 되지만 비정상은 throw를 통해 코드를 터트리는 게 좋다 비정상도 리턴을 통해 코드를 짜면 복잡해지고 가독성도 떨어진다
notion image

예외처리로 바꾼 코드

package ex15; class Repository02 { // 1이면 존재하는 회원, -1이면 존재하지 않음 void findIdAndPw(String id, String pw) { System.out.println("레포지토리 findIdAndPw 호출됨"); if (!(id.equals("ssar") && pw.equals("5678"))) { throw new RuntimeException("아이디 혹은 비번 틀림"); } } } // 책임 : 유효성 검사 class Controller02 { 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 Try04 { public static void main(String[] args) { Controller01 con = new Controller01(); try { con.login("ssar", "123"); } catch (Exception e) { System.out.println(e.getMessage()); } } }
notion image
Share article

gunwoo