[JAVA]56.예외처리

손영민's avatar
Mar 09, 2025
[JAVA]56.예외처리
 

1.강제 익셉션

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

2.호출한 쪽에서 익셉션 잡아채기

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()); } } }
 

3.로그인예제

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); } }
 
 
 
 
 

4.로그인예제 수정

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

sson17