예외는 크게 두가지 예외가 있음
컴파일 Exception (실행 전에 예상 가능한 예외)
코드를 작성할 때 에러를 띄움
런타임 Exception (실행 전에는 예상이 불가능한 예외)
런타임(실행) 도중 에러를 띄움
예외 처리 위임
package ex08.example2;
class Cal3 {
// 예외처리 권한호출자에게 위임
// Exception가 쓰여있으면 호출자가 예외처리 하지 않으면 오류를 발생시킴(발생시키는게 목적임)
// RuntimeException가 쓰여있으면 오류를 발생 시키지는 않으나, 런타임 오류는 발생함
// 사용하지 않아도 예외를 위임시키긴 하지만,
// Exception를 씀으로써 사용자로 하여금 예외처리를 강제시킬 수 있음
void divide(int num) throws Exception {
System.out.println(10 / num);
}
}
class Cal5 {
// 예외처리를 직접담당함
void divide(int num) {
try {
System.out.println(10 / num);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public class TryEx05 {
public static void main(String[] args) {
Cal3 c3 = new Cal3();
try {
c3.divide(0);
} catch (Exception e) {
System.out.println("0으로 나누지 마요");
}
}
}
예외 처리는 try catch 문으로 하는것이 좋음
if문을 사용한 예외처리
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);
}
}
try 문을 사용한 예외처리
package ex08.example2;
// 책임 : 데이터베이스 상호작용
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("ssar", "1234");
System.out.println("회원가입 성공");
} catch (RuntimeException e) {
System.out.println(e.getMessage());
}
}
}