[JAVA] 15. 예외처리

최재원's avatar
Feb 17, 2025
[JAVA] 15. 예외처리
notion image

1. CheckedException

package ex15; public class Check01 { public static void main(String[] args) { System.out.println("시작"); try { Thread.sleep(5000); } catch (InterruptedException e) { System.out.println("도중에 꺼졌는데 괜찮아"); throw new RuntimeException(e); } System.out.println("끝"); } }
  • Thread.sleep(5000)에서 빨간줄이 나타나며 예외가 난다.
  • try catch를 사용해 예외처리
package ex15; import java.io.FileNotFoundException; import java.io.FileReader; public class Check02 { public static void main(String[] args) { try { FileReader fr = new FileReader("c:/hello/good.txt"); } catch (FileNotFoundException e) { System.out.println("파일을 내가 직접 생성 \"c:/hello/good.txt\""); } } }
  • FileReader에서 빨간줄이 나타나며 예외발생
  • try catch를 사용해 예외처리

2. RuntimeException

1. 강제로 예외를 만드는 방법

package ex15; public class Try01 { public static void main(String[] args) { throw new ArithmeticException("강제로 만든 익셉션"); } }
  • throw를 사용해 강제로 예외를 만들 수 있다.
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); } }
  • 0으로 나누는 상황이 오면 예외처리를 한다.
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()); } } }
A.start(false) 처럼 호출한 위치에서 try catch를 사용해 예외 처리를 할 수 있다.

2-1. 예제(if-else)

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-2. 예제(try-catch)

package ex15; class Repository04 { // 1이면 존재하는 회원, -1이면 존재하지 않음 void findIdAndPw(String id, String pw) { System.out.println("레포지토리 findIdAndPw 호출됨"); if (!(id.equals("ssar") && pw.equals("5678"))) { throw new RuntimeException("아이디 혹은 비번 틀림"); } } } // 책임 : 유효성 검사 class Controller04 { 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자 이상이어야 해요"); } Repository04 repo = new Repository04(); repo.findIdAndPw(id, pw); } } public class Try04 { public static void main(String[] args) { Controller04 con = new Controller04(); try { con.login("ssar", "123"); } catch (Exception e) { System.out.println(e.getMessage()); } } }
  • 실패한 경우만 예외처리를 하면 된다.
Share article

jjack1