예외 처리

Jan 02, 2024
예외 처리

예외(Exception) : 잘못된 코드, 부정확한 데이터, 예외적인 상황에 의한 오류 발생
 
💡
RuntimeException : 실행시 발생
 
💡
ctrl + alt + t : Surround With
 
notion image
 
Thowable - getMessage(O)
Exception - getMessage(X)
RuntimeException - getMessage(X)
ArithMethicException - getMessage(X)
 
package ex08; import java.util.Scanner; public class DivideByZero { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int num = sc.nextInt(); int result = 0; try { result = 10 / num; } catch (Exception e) { System.out.println("0으로 나누면 안되요"); System.out.println(e.getMessage()); // throw new RuntimeException(e); } System.out.println("나눗셈 결과 : " + result); } }
notion image
notion image
 
e.printStackTrace(); // 오류 추적
package ex08; import java.util.Scanner; public class DivideByZero { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int num = sc.nextInt(); int result = 0; try { result = 10 / num; } catch (Exception e) { System.out.println("0으로 나누면 안되요"); System.out.println(e.getMessage()); e.printStackTrace(); // 오류 추적 // throw new RuntimeException(e); } System.out.println("나눗셈 결과 : " + result); } }
notion image
notion image
 
오류가 발생하기 전에는 어떤 예외가 필요한지 알 수 가 없음
 
throw : 호출자한테 예외가 위임되서 호훌자가 처리할 수 있음
throw new RuntimeException("0으로 나눌 수 없어요"); // 강제 메세지 부여
notion image
 
예외는 다 같이 아니라 따로 나누는 것이 좋음
문법적으로 멀티 catch가 가능하지만 나누는 것이 좋음
 
finally : 항상 실행됨
 
예외의 종류
CompileException = Checked-Exception : 실행 전에 알 수 있는 오류
RuntimeException : 실행해봐야 아는 오류
 
package ex08.example2; class Cal2 { public void divide(int num) throws Exception { System.out.println(10 / num); } } public class TryEx01 { public static void main(String[] args) { Cal2 c2 = new Cal2(); c2.divide(2); // 실행전 오류를 알려줌 } }
 
package ex08.example2; class Cal2 { // RuntimeException = 엄마가 알려주지 않았을 때 public void divide(int num) throws Exception { System.out.println(10 / num); } } public class TryEx01 { public static void main(String[] args) { Cal2 c2 = new Cal2(); try { c2.divide(0); } catch (Exception e) { System.out.println("0으로 나눌 수 없어요"); } } }
notion image
 
package ex08.example2; public class TryEx02 { public static void main(String[] args) { throw new RuntimeException("오류 강제 발생"); } }
notion image
 

연습문제


package ex08.example2; // 책임 : 데이터베이스 상호작용 class Repository { void insert() { System.out.println("레포지토리 insert 호출됨"); } void select() { } } // 책임 : 유효성 검사 class Controller { String join(String id, String pw) { if(id.length() < 4) { return "id의 길이가 4자 이상이어야 합니다."; } System.out.println("컨트롤러 회원가입 호출됨"); Repository repo = new Repository(); repo.insert(); return "회원가입이 완료되었습니다."; } void login() { System.out.println("컨트롤러 로그인 호출됨"); } } public class TryEx03 { public static void main(String[] args) { Controller con = new Controller(); String message = con.join("ssa", "1234"); System.out.println(message); } }
notion image
 
조건문으로 검사
package ex08.example2; // 약속 : 1은 정상, 2는 id 제약조건 실패, 3은 pw 제약조건 실패 // 책임 : 데이터베이스 상호작용 class Repository { int insert(String id, String pw) { System.out.println("레포지토리 insert 호출됨"); if (id.length() < 4) { return 2; } if (pw.length() > 50) { return 3; } return 1; } } // 책임 : 유효성 검사 class Controller { String join(String id, String pw) { System.out.println("컨트롤러 회원가입 호출됨"); if (id.length() < 4) { return "유효성검사 : id의 길이가 4자 이상이어야 합니다."; } Repository repo = new Repository(); int code = repo.insert(id, pw); if (code == 2) { return "id가 잘못됐습니다"; } if (code == 3) { return "pw가 잘못됐습니다"; } return "회원가입이 완료되었습니다"; } } public class TryEx03 { public static void main(String[] args) { Controller con = new Controller(); String message = con.join("ssar", "123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789"); System.out.println(message); } }
notion image
 
package ex08.example2; // 약속 : 1은 정상, 2는 id 제약조건 실패, 3은 pw 제약조건 실패 // 책임 : 데이터베이스 상호작용 class Repository2 { void insert(String id, String pw) { System.out.println("레포지토리 insert 호출됨"); if (id.length() < 4) { throw new RuntimeException("DB: id의 길이가 4자 이상 이어야 합니다."); } if (pw.length() > 50) { throw new RuntimeException("DB: pw의 길이가 50자 이하 이어야 합니다."); } } } // 책임 : 유효성 검사 class Controller2 { void join(String id, String pw) throws RuntimeException{ // join에게 위임 System.out.println("컨트롤러 회원가입 호출됨"); if (id.length() < 4) { throw new RuntimeException("Controller : id의 길이가 4자 이상 이어야 합니다."); // main의 join에게 던짐 } Repository2 repo = new Repository2(); repo.insert(id, pw); } } public class TryEx04 { public static void main(String[] args) { Controller2 con = new Controller2(); con.join("ssar", "1234"); System.out.println("회원가입 성공"); // 에러를 위임 받음 } }
notion image
try/catch로 묶기
package ex08.example2; // 약속 : 1은 정상, 2는 id 제약조건 실패, 3은 pw 제약조건 실패 // 책임 : 데이터베이스 상호작용 class Repository2 { void insert(String id, String pw) { System.out.println("레포지토리 insert 호출됨"); if (id.length() < 4) { throw new RuntimeException("DB: id의 길이가 4자 이상 이어야 합니다."); } if (pw.length() > 50) { throw new RuntimeException("DB: pw의 길이가 50자 이하 이어야 합니다."); } } } // 책임 : 유효성 검사 class Controller2 { void join(String id, String pw) throws RuntimeException{ // join에게 위임 System.out.println("컨트롤러 회원가입 호출됨"); if (id.length() < 4) { throw new RuntimeException("Controller : id의 길이가 4자 이상 이어야 합니다."); // main의 join에게 던짐 } Repository2 repo = new Repository2(); repo.insert(id, pw); } } public class TryEx04 { public static void main(String[] args) { Controller2 con = new Controller2(); try { con.join("ssar", "1234"); System.out.println("회원가입 성공"); } catch (RuntimeException e) { System.out.println("e.getMessage()"); } } }
notion image

 
레이어 > 책임을 분리

연습문제


package ex08.example2; class Cal3 { void divide(int num) throws Exception { System.out.println(10 / num); } } class Cal4 { void divide(int num) { try { System.out.println(10 / num); } catch (Exception e) { System.out.println("no no by zero"); } } } public class TryEx05 { public static void main(String[] args) { Cal3 c3 = new Cal3(); try { c3.divide(0); } catch (Exception e) { System.out.println("0으로 나누지 마요"); } } }
notion image
 
package ex08.example2; class Cal3 { void divide(int num) throws Exception { System.out.println(10 / num); } } class Cal4 { void divide(int num) { try { System.out.println(10 / num); } catch (Exception e) { System.out.println("no no by zero"); } } } public class TryEx05 { public static void main(String[] args) { Cal3 c3 = new Cal3(); try { c3.divide(0); } catch (Exception e) { System.out.println("0으로 나누지 마요"); } Cal4 c4 = new Cal4(); c4.divide(0); } }

 
💡
라이브러리 작성자가throw를 사용하여 try/catch를 사용한 경우
>소유권을 가져올 수 있음
라이브러리 작성자가 try/catch만 사용한 경우 > 소유권을 뺏김
Share article
RSSPowered by inblog