
예외 처리
- 자바에서 나타나는 에러들을 예외(exception)이라고 한다.
- 예외의 종류에는 크게 런타임 익셉션(RuntimeException)과 컴파일 익셉션(CompileException)이 있다.
- 자바에서는 예외를 ‘try-catch’를 사용하여 처리한다. →이때, try에는 예외가 발생할 가능성이 있는 문장을 catch에는 그 예외를 처리할 코드를 넣는다.
- 예외 처리 할 때는 예외의 종류에 따라 catch를 나눠서 하는 것이 좋다.
런타임 익셉션(RuntimeException)과 컴파일 익셉션(CompileException)에 대해 알아보자!
런타임 익셉션은 컴파일 된 후 실행 시에 발생하는 예외를 뜻하며, 비강제성을 가진다
→ 데이터 유효성 검사 등
컴파일 익셉션은 문제가 생기면 컴파일 자체가 불가, 컴파일 과정에서 발생하는 예외를 뜻하며, 강제성을 가진다
→ 문법적 오류
Throws
- 메서드를 선언 할 때 사용한다.
- 메서드가 예외를 처리하지 않고, Throws로 선언한 메서드를 호출한 곳으로 예외를 던진다.
Throws와 Throw의 차이점!
Throws는 메서드 선언 부분에 사용한다.
→ 메서드 자체에 사용
Throw는 메서드 실행 중에 특정 조건에서 예외를 직접 발생시키는 데 사용됩니다.
→ 예외를 직접적으로 출력하기 위해 사용
- Try-catch 기본 예제
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으로 나눌 수 없어요");
}
}
}
- Throw 기본 예제
package ex08.example2;
public class TryEx02 {
public static void main(String[] args) {
throw new RuntimeException("오류 강제 발생"); // 강제로 오류를 발생 시키는 것
}
}
- Try-catch 심화 예제
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);
}
}
- Throws 사용 예제
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());
}
}
}
- Code 리펙토링 진행
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);
}
}
Share article