[java] checked exception/ unchecked exception

심심이·2024년 3월 2일
0

java

목록 보기
36/46

자바의 예외는 크게 3가지로 나눌 수 있다.

  • 체크 예외(Checked Exception)
  • 에러(Error)
  • 언체크 예외(Unchecked Exception)

에러

개발자가 처리 불가능(메모리 부족 문제, 스택오버플로우 등 복구할 수 없는 경우)

체크 예외(Checked Exception)

  • runtimeException의 자식 클래스에 해당하지 않는 경우이다. (Exception 클래스의 하위 클래스이다.)
    try/catch 로 예외 처리를 해주거나 throw로 떠넘겨 줘야 된다.

언체크 예외(unchecked exception)

  • runtimeException의 자식 클래스들
  • 에러 처리를 강제하지 않음. 떠넘기는 경우 아무 처리 하지 않아도 됨
  • ArrayIndexOutOfBoundsException
  • NullPointerException 등
  • 개발자들의 실수로 발생하기 때문에 에러 처리 강제하지 않음

컴파일러가 에러처리를 확인하지 않는 RuntimeException 클래스들은 unchecked 예외라고 부르고
예외처리를 확인하는 Exception 클래스들은 checked 예외라고 부른다.

롤백 여부

체크 예외 : Rollback이 되지 않고 트랜잭션이 commit까지 완료됨
언체크 예외 : Rollback이 됨.

RuntimeException 처리

class Amount {
    private String currency;
    private int amount;

    public Amount(String currency,int amount) {
        super();
        this.currency = currency;
        this.amount = amount;
    }

    public void add(Amount that) {
        if(!this.currency.equals(that.currency)) { // 통화가 일치하지 않을 때
            throw new RuntimeException("Currencies Don't Match"); 
            //예외를 떠넘긴 뒤 main메소드에서 처리해서 ui에 올바른 메세지 출력 및 로그남김
        }
        this.amount = this.amount + that.amount;
    }

    public String toString() {
        return amount + " " + currency;
    }

}


public class ThrowingExceptionRunner {
    public static void main(String[] args) {
        Amount amount1 = new Amount("USD", 10);
        Amount amount2 = new Amount("EUR", 20); // EUR값이 들어와도 USD로 처리하는 오류 발생
        amount1.add(amount2);
        System.out.println(amount1); //자동으로 tostring 붙음
    }
}

exception 처리



class Amount {
    private String currency;
    private int amount;

    public Amount(String currency,int amount) {
        super();
        this.currency = currency;
        this.amount = amount;
    }

    public void add(Amount that) throws Exception {
//        if(!this.currency.equals(that.currency)) { // 통화가 일치하지 않을 때
//            throw new RuntimeException("Currencies Don't Match"); //예외를 떠넘긴 뒤 main메소드에서 처리해서 ui에 올바른 메세지 출력 및 로그남김
//        }
        if(!this.currency.equals(that.currency)) { // 통화가 일치하지 않을 때
            throw new Exception("Currencies Don't Match" + this.currency + " & " + that.currency); //예외를 떠넘긴 뒤 main메소드에서 처리해서 ui에 올바른 메세지 출력 및 로그남김
        }
        this.amount = this.amount + that.amount;
    }

    public String toString() {
        return amount + " " + currency;
    }

}


public class ThrowingExceptionRunner {
    public static void main(String[] args) throws Exception {
        Amount amount1 = new Amount("USD", 10);
        Amount amount2 = new Amount("EUR", 20); // EUR값이 들어와도 USD로 처리하는 오류 발생
        amount1.add(amount2); // add가 checked exception 넘김
        // 이제 1. try~catch 2. throws Exception 해야 함 큰단위의 경우 1번으로 처리
        // 실행시  Currencies Don't Match 메시지 출력
        // add에 throws Exception ==> 메인에서 불러올 때 throws Exception
        System.out.println(amount1); //자동으로 tostring 붙음
    }
}


사용자 exception 처리


class Amount {
    private String currency;
    private int amount;

    public Amount(String currency,int amount) {
        super();
        this.currency = currency;
        this.amount = amount;
    }

    public void add(Amount that) throws CurrenciesDoNotMatchException {
        if(!this.currency.equals(that.currency)) { // 통화가 일치하지 않을 때
            throw new CurrenciesDoNotMatchException("Currencies Don't Match" + this.currency + " & " + that.currency);
        }
        this.amount = this.amount + that.amount;
    }

    public String toString() {
        return amount + " " + currency;
    }

}

// 사용자 예외 처리 만들기
class CurrenciesDoNotMatchException extends Exception {
    public CurrenciesDoNotMatchException(String msg) { //생성자
        super(msg); //예외 시 메시지 전달 
    }
}



public class ThrowingExceptionRunner {
    public static void main(String[] args) throws CurrenciesDoNotMatchException { //사용자예외처리함수
        Amount amount1 = new Amount("USD", 10);
        Amount amount2 = new Amount("EUR", 20); // EUR값이 들어와도 USD로 처리하는 오류 발생
        amount1.add(amount2);
        System.out.println(amount1); //자동으로 tostring 붙음
    }
}

런타임 예외 상속하는 사용자예외처리

class Amount {
    private String currency;
    private int amount;

    public Amount(String currency,int amount) {
        super();
        this.currency = currency;
        this.amount = amount;
    }

    public void add(Amount that){
        if(!this.currency.equals(that.currency)) { // 통화가 일치하지 않을 때
            throw new CurrenciesDoNotMatchException("Currencies Don't Match" + this.currency + " & " + that.currency);
        }
        this.amount = this.amount + that.amount;
    }

    public String toString() {
        return amount + " " + currency;
    }

}

// 사용자 예외 처리 만들기
class CurrenciesDoNotMatchException extends RuntimeException { // 런타임 예외를 상속받는 예외 생성 : throw 불필요
    public CurrenciesDoNotMatchException(String msg) { //생성자
        super(msg); //예외 시 메시지 전달
    }
}



public class ThrowingExceptionRunner {
    public static void main(String[] args) { // 런타임 예외를 상속받는 예외  : throw 불필요
        Amount amount1 = new Amount("USD", 10);
        Amount amount2 = new Amount("EUR", 20); // EUR값이 들어와도 USD로 처리하는 오류 발생
        amount1.add(amount2);
        System.out.println(amount1); //자동으로 tostring 붙음
    }
}

결론>
checked exception : 예외처리해줘야함
unchecked exception(runtime exception) : 예외처리 할필요 없음

사용자 대상을 고려해서 만든다. 예외처리를 해줘야 한다면 checked exception, 할 수 있는 일이 없다면 runtimeException

주의>
exception 처리 시 부모클래스의 exception 이 맨 아래에 나와야 한다.


레퍼런스
https://devlog-wjdrbs96.tistory.com/351

profile
개발하는 심심이

0개의 댓글

관련 채용 정보