throw : 직접 오류를 발생
if vs throw
if : 예외가 발생할 경우를 직접 만들어야 함, 자료형이 무조건 일치해야 함
throw : 예외가 발생한 후 처리 가능, 자료형 무시 가능
1. throw
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());
}
}
}
- false로 start → m1에 false → 오류 발생 (throw new RuntimeException)
- main에서 catch : 오류 발생 string 출력

2. 응용
- if로 예외 처리를 할 경우
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);
}
}
- Controller : 오류 처리를 위해 String 클래스로 처리
- 다른 자료형(클래스)을 반환할 수 없음
- 오류에 대한 클래스를 사전에 설정 : 코드가 길어지고, 관리가 불편
- throw로 예외 처리
package ex15;
class Repository {
// 1이면 존재하는 회원, -1이면 존재하지 않음
void findIdAndPw(String id, String pw) {
System.out.println("레포지토리 findIdAndPw 호출됨");
if (!(id.equals("ssar") && pw.equals("5678"))) {
throw new RuntimeException("아이디 혹은 비번 틀림");
}
}
}
// 책임 : 유효성 검사
class Controller {
void login(String id, String pw) {
System.out.println("컨트롤러 로그인 호출됨");
// exception throw > 일일이 클래스를 만들지 않고 string return 가능
if (id.length() < 4) {
throw new RuntimeException("id 길이가 최소 4자 이상이어야 해요");
}
if (pw.length() < 4) {
throw new RuntimeException("pw 길이가 최소 4자 이상이어야 해요");
}
Repository repo = new Repository();
repo.findIdAndPw(id, pw);
}
}
public class Try03 {
public static void main(String[] args) {
Controller con = new Controller();
try {
con.login("ssar", "123");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
- 오류 처리가 편함 : throw문을 통해 오류 메시지를 출력할 수 있음
- 오류 케이스만 만들어 처리하면 되므로 유지보수 편리
- 메서드 타입에 국한되지 않음 : 자유롭게 string 출력 가능
Share article