예외 처리 Exception

김민영·2023년 1월 24일
0

Java

목록 보기
14/14
  • 에러 error : 응용프로그램 실행 오류
  • 예외 exception : 사용자의 잘못된 조작 또는 개발자의 잘못된 코딩으로 인해 발생하는 프로그램 오류
  • 자바에서는 예외를 클래스로 관리한다.
    • 모든 예외는 java.lang.Exception 클래스를 상속받는다.

예외 종류

일반 예외 Exception

  • 컴파일 체크 예외.
  • 예외 처리 코드가 없으면 컴파일 오류 발생
  • Exception을 상속 받지만, RuntimeException을 상속 받지 않음

실행 예외 Runtime Exception

  • 컴파일 과정에서 예외 코드를 검사하지 않는 예외.
  • Exception을 상속받고, java.lang.RuntimeException을 상속 받음.

NullPointerException (NPE)

  • 객체 참조가 없는 상태 (null 상태) 값을 가지고 있는 참조 변수로 객체 접근 연산자인 . 를 사용했을 때 발생.
  • 객체가 없는 상태(null)에서 객체를 사용하려 할 때 발생

ArrayIndexOutOfBoundsException

  • 배열에서 할당된 배열의 인덱스 범위를 초과해서 사용하는 경우

NumberFormatException

  • 문자열을 정수로 변환 : Integer.parseInt(String s)
  • 문자열을 실수로 변환 : Double.parseDouble(String s)
  • Integer, Double : 포장(Wrapper) 클래스
    • 본 자료타입 (primitive type)을 객체로 다루기 위해 사용하는 클래스
  • 숫자로 변환할 수 없는 문자가 오면 에러가 발생함.

ClassCaseException

  • Casting : 타입변환. 상위클래스 - 하위클래스, 구현클래스 - 인터페이스 간 발생
  • 그 외의 경우, 억지로 타입변환을 시도할 경우 에러 발생

예외 처리

try, catch

public class test {

    public static void main(String[] args) throws IOException {

        int c;
        try {
            c = 4 / 0;
        } catch (ArithmeticException e) {
            c = -1;
        } catch (NumberFormatException e) {
            c = 1;
        }
        System.out.println(c);
    }
}

finally

  • try 에서 에러가 발생하는 곳 뒤의 코드는 실행되지 않는다.
public class test {

    public void shouldBeRun() {
        System.out.println("ok thanks.");
    }

    public static void main(String[] args) throws IOException {

        test tes = new test();

        int c;
        try {
            c = 4 / 0;
            tes.shouldBeRun(); // 실행되지 않는다.
        } catch (ArithmeticException e) {
            c = -1;
        } catch (NumberFormatException e) {
            c = 1;
        }
        System.out.println(c);
    }
}
  • 예외에 상관 없이 실행하고 싶은 것은 finally 안에 넣는다.
public class test {

    public void shouldBeRun() {
        System.out.println("ok thanks.");
    }

    public static void main(String[] args) throws IOException {

        test tes = new test();

        int c;
        try {
            c = 4 / 0;
        } catch (ArithmeticException e) {
            c = -1;
        } catch (NumberFormatException e) {
            c = 1;
        } finally {
            tes.shouldBeRun(); // 실행된다.
        }
        System.out.println(c);
    }
}

throw

  • 강제로 예외를 발생 시키기.
  • 자바에서 정하는 예외는 아니지만, 사용자 지정 예외를 발생시킬 수 있다.
  • 파이썬의 raise라고 생각하면 될 듯 하다.
public class test {

    public void shouldBeRun() {
        System.out.println("ok thanks.");
    }

    public static void main(String[] args) throws IOException {

        test tes = new test();

        int c;
        try {
            c = 4 / 1;
            System.out.println(c);
            throw new Exception();
        } catch (Exception e) {
            System.out.println("에러 강제 발생");
        } finally {
            tes.shouldBeRun(); // 실행된다.
        }
    }
}

throws

  • 예외를 상위로 미루어 처리
  • 예외를 따로 처리하고, throws 구문에 발생할 예외를 적어 놓음.
  • 만들어진 메소드 throws 발생할 예외 []

https://bvc12.tistory.com/196

Transaction

  • transaction : 하나의 작업 단위
  • 에러 발생 시, 작업 전체에 대해서 롤백이 필요할 때, throws를 사용해서 작업의 각 단계 모두 예외 처리를 한다.
    • 각 단계마다 예외 처리를 하면 뒤죽박죽이 될 수 있음.

https://wikidocs.net/229

profile
노션에 1차 정리합니당 - https://cream-efraasia-f3c.notion.site/4fb02c0dc82e48358e67c61b7ce8ab36?v=

0개의 댓글