Exception

#exception #catch - try
Jan 02, 2024
Exception
Contents
try - catch
CompileException (CheckedException) - 미리 잡을 수 있는 예외 오류
throws Exception - 엄마가 미리 알려줬을 때
RuntimeException - 실행 시 알 수 있는 예외 오류 /  부모가 알려주지 않았을 때
printStackTrace - 오류 추적
CompileException (CheckedException) - 미리 잡을 수 있는 예외 오류 throws Exception - 엄마가 미리 알려줬을 때 RuntimeException - 실행 시 알 수 있는 예외 오류 / 부모가 알려주지 않았을 때 printStackTrace - 오류 추적
Exception 부모가 자식한테 미리 알려준다.
RuntimeException 자식이 스스로 선택할 수 있다.
Exception 부모가 자식한테 미리 알려준다. RuntimeException 자식이 스스로 선택할 수 있다.
throws Exception
메서드 선언부에서 해당 메서드에 발생할 수 있는 모든 예외를 선언하는 것 호출자에게 예외 처리 책임을 넘기는 역할
throw new RuntimeException("")
메서드 내에서 직접 예외를 발생시키는 것 예외 상황이 발생하였음을 명시적으로 알리는 역할

try - catch

public class TryEx01 { public static void main(String[] args) { String name = null; try { name = null; System.out.println(name.length()); } catch (Exception e) { throw new RuntimeException(e); } } }
throw new RuntimeException(e)에서 e대신 “원하는 경고 메세지”로 대체 가능 catch에서 Exception 대신에 밑에 오류에 뜨는 NullException, RuntimeException으로 입력 가능
notion image
 
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(); try { c2.divide(0); } catch (Exception e) { System.out.println("0으로 나눌 수 없어요."); } } }
CheckedException - 미리 잡을 수 있는 예외 오류
public class TryEx02 { public static void main(String[] args) { throw new RuntimeException("오류 강제 발생"); } }
오류 강제화
package ex08.example02; // 책임 : 데이터베이스 상호작용, 제약조건 검사 class Repository{ String insert(String id, String pw){ if (id.length()<4){ return "id의 길이가 4자 이상이어야 합니다."; } System.out.println("레포지토리 insert 호출"); return "DB에 정상 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(); String message = repo.insert(id,pw); if (!message.equals("DB에 정상 insert 되었습니다.")){ return message; } return "회원가입이 완료되었습니다."; } void login(){ System.out.println("컨트롤러 로그인 호출"); } } public class TryEx03 { public static void main(String[] args) { Controller con = new Controller(); String message = con.join("ssar","1234"); System.out.println(message); } }
if로 복잡하게 만든 코드
package ex08.example02; // 약속 : 1은 정상, 2는 id 제약조건 실패, 3은 pw 제약조건 실패 // 책임 : 데이터베이스 상호작용 class Repository01 { 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 Controller01 { String join(String id, String pw) { System.out.println("컨트롤러 회원가입 호출됨"); if (id.length() < 4) { return "유효성검사 : id의 길이가 4자 이상이어야 합니다."; } Repository01 repo = new Repository01(); int code = repo.insert(id, pw); if (code == 2) { return "id가 잘못됐습니다"; } if (code == 3) { return "pw가 잘못됐습니다"; } return "회원가입이 완료되었습니다"; } } public class TryEx04 { public static void main(String[] args) { Controller01 con = new Controller01(); String message = con.join("ssar", "123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789"); System.out.println(message); } }
TryEx03 코드의 모듈화
package ex08.example02; class Repository02 { void insert(String id, String pw) throws RuntimeException { 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 Controller02 { void join(String id, String pw) throws RuntimeException{ System.out.println("컨트롤러 회원가입 호출됨"); if (id.length() < 4) { throw new RuntimeException ("Controller : id의 길이가 4자 이상 이어야 합니다."); } Repository02 repo = new Repository02(); repo.insert(id, pw); } } public class TryEx05 { public static void main(String[] args) { Controller02 con = new Controller02(); try { con.join("ssa", "1234"); System.out.println("회원가입 성공"); } catch (RuntimeException e) { System.out.println(e.getMessage()); } } }
TryEx04 리팩토링 및 try-catch 사용
 
package ex08.example02; 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 TryEx06 { public static void main(String[] args) { Cal3 c3 = new Cal3(); try { c3.divide(0); } catch (Exception e) { System.out.println("0으로 나누지 마요"); } Cal4 cal4 = new Cal4(); cal4.divide(0); } }
 
Share article

from-web-developer