예외처리

이소연's avatar
Aug 05, 2024
예외처리

예외처리

코드를 짜보고 터지면 그거를 토대로 예외처리를 함.
서비스 전 최대한 많은 경우의 수를 넣어보면 좋음
우리가 예외 전부를 알 수 없으니 베타 테스트로 고객들 의견을 받아 모아 그때에 추가/변경함.
 
💡
try _ catch 만드는 단축키
ctrl + alt +t (6.try catch)

Try-catch 사용법

ex) 호스로 벽 얼룩 청소하기
try{ 예외 발생할 수 있는 코드} ex) 호스로 얼룩을 쏘는 데 벽 대신 사람이 맞음 _ 예외상황
catch{발생한 예외를 처리하는 코드} ex) 그럴 때는 사과를 해 _ 예외상황 처리
finally{ 공통적으로 마무리해야하는 부분 }ex) (호스)뚜껑닫기
(여기서 try, catch에서 따로 각 뚜껑을 닫히는 문장을 추가해도 되지만 2번 적어야 해서 귀찮
.→finally로 묶어서 간편하게 적음)
(finally는 생략 가능)
[상속 및 메서드 상태] Throwable --> getMessage() Exception --> x RuntimeException --> x ArithmeticException --> x Throwable(최초 부모)꺼를 다 땡겨쓰는 것임
notion image
 

예외[Exception]의 종류

  1. 예상가능한 예외(Checked Exception)
: 코드 적을 때 오류가 뜸(컴파일 오류_Compile Exception)
ex) 엄마가 아들한테 심부름을 시키는 데 예상 가능한 일들을 미리 말해주는 것.
~걸을 때 돌 조심, 돈 줄 때 이런 부분 조심 등
 
  1. 예상치 못한 예외(Unchecked Exception )
: 실행 시에 오류 뜸(실행오류_Runtime Exception)
_즉 코드 적을 때는 아무 이상 없다가 실행을 하면 안되는 경우
ex) 엄마가 아들한테 (아무 말 없이) 심부름을 시킴.
~아들이 심부름을 하면서 오류들을 발견.
-Arithmetic / nullpointer/Arrayindexoutofbound exception 등 : 종류는 중요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(); // 컨트롤 + 알트 + t int result = 0; try { result = 10/num; } catch (Exception e) { //Exception e = new ArithmeticException() //이 예제는 예제 출력설명을 주석에 따라 선택할 수 있다. System.out.println("0으로 나누면 안되요"); // System.out.println(e.getClass());_오류위치(getclass)를 알려줌 System.out.println(e.getMessage()); // 여기서 예외 처리 // e.printStackTrace(); //_콘솔에서 예외오류말해줌 // throw new RuntimeException(("0으로 나눌 수 없어요"));_직접 입력가능 } System.out.println("나눗셈 결과는: " + result); // 실행시 오류 런타임 인셉션 } } //Throwable --> getMessage() //Exception --> x //RuntimeException --> x //ArithmeticException --> x ----------------------------------------------------------------------------- } catch (Exception e) { //Exception e = new ArithmeticException() System.out.println("0으로 나누면 안되요"); System.out.println(e.getMessage()); // 여기서 예외 처리 // System.out.println(e.getClass()); // e.printStackTrace(); // // throw new RuntimeException(("0으로 나눌 수 없어요")); } 이부분 다 주석 처리하고 throw new RuntimeException(("0으로 나눌 수 없어요")); 부분만 주석 해제하면 강제적으로 호출 가능
notion image
notion image
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으로 나눌 수 없어요"); } } }
예외 exception와 에러 error의 차이
내용 강제 입력
notion image
 
이 경우 반환값을 전달받고 전달 받아야 함. (코드가 복잡해짐)
notion image
 
notion image
notion image
notion image
추가로)
notion image
 
package ex08.example2; //따로 적은 거 //책임 : 데이터베이스 상호작용 //db 제약조건?-v 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; } repo.insert(id, pw); 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); } }
그래서 반환값을 직접 적어주면,
package ex08.example2; // 약속 : 1은 정상, 2는 id 제약조건 실패, 3은 pw 제약조건 실패 // 책임 : 데이터베이스 상호작용 class Repository2 { 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 Controller2 { void join(String id, String pw) throws RuntimeException { System.out.println("컨트롤러 회원가입 호출됨"); if (id.length() < 4) { throw new RuntimeException("Controller : id의 길이가 4자 이상 이어야 합니다."); } Repository2 repo = new Repository2(); repo.insert(id, pw); } } public class TryEx04 { public static void main(String[] args) { Controller2 con = new Controller2(); try { con.join("ssa", "1234"); System.out.println("회원가입 성공"); } catch (RuntimeException e) { System.out.println(e.getMessage()); } } }
 
Throw하면 생성자에게 위임 / throw는 재성님에게 강아지 위임?
notion image
notion image
notion image
컨트롤러 호출하고 if throw에 걸려서 contro문구 나오고 catch로 감?-v
💡
alt + enter : 자동완성 기능
 
throw RuntimeException시에는 divide가 오류 안 뜨고(실행 시에 오류 찾음) _예외구체적으로 다 적어야 함.
Exception시에는 개발자가 작성자가 잘 못할 경우를 미리 생각해서 (강제로) try catch구문 만들게 함.-v
notion image
notion image
notion image
notion image
throw 해서 메인으로 위임하고 메인에서 try catch로
그러면 if 해서 return을 받고받고 안해도 됨.
 
throw는 우리가 소유권을 가져올 수 있음
notion image
이 경우는 throw를 하면 예외처리를 호출자한테 떠넘김.
notion image
notion image
 
Share article

Coding's note