자바 예외처리

웅평·2023년 12월 11일

예외처리

  • 컴파일 오류 : 코드에 문제가 있는 것
  • 런타임 오류 : 실행하는 과저에서 오류가 있는 것 ex) index 크기보다 벗어나는 경우
  • error : 코드를 수습할 수 없는경우 ex) 재귀의 스택오브플로우
  • 예외(exception) : 수습가능한 경우 ex) 파일 경로가 없는 경우

try catch

문법

try {
} catch(Exception e) {
}

예제

try {
            System.out.println(3 / 0);
        } catch (Exception e) {
            System.out.println("문제 원인 : " + e.getMessage());
            // e.printStackTrace();
        }

getMessage()룰 통해서 오류 내용을 알 수 있다

index 크기보다 벗어나는 경우

try {
            int[] arr = new int[3];
            arr[5] = 0;
        } catch (Exception e) {
            System.out.println("문제 원인 : " + e.getMessage());
            // e.printStackTrace();
        }

printStackTrace()는 getMessage()와 비슷함

복수의 catch문

  • 하나의 try문에 여러개의 catch가 올 수 있다
  • catch 절을 사용할 때는 범위가 작은 순 즉 자식클래스 부터 와야한다
  • 예외자료형의 Object, Throwable, Exception 순으로 크다
  • 메소드 안에서 예외가 발생이 될떄 예외처리를 메소드 호출하는 쪽으로 잔파하기 위해 사용
try {
            int[] arr = new int[3];
            arr[7] = 7;
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("index 범위를 벗어났습니다");
        } catch (Exception e) {
            System.out.println("문제 원인 : " + e.getMessage());
            e.printStackTrace();
        }

index를 위에 있는 catch문부터 실행

try {
            String s = null;
            System.out.println(s.toLowerCase());
        } catch (ArithmeticException e) {
            System.out.println("잘못 계산했습니다");
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("index 범위를 벗어났습니다");
        } catch (ClassCastException e) {
            System.out.println("잘못된 형변환입니다.");
        } catch (Exception e) {
            System.out.println("그 외의 문제 원인 : " + e.getMessage());
            e.printStackTrace();
        }

두개의 예외처리 합치기

try {
            System.out.println(3 / 0);
        } catch (ArithmeticException | ArrayIndexOutOfBoundsException e) {
            System.out.println("실수");
        } catch (ClassCastException e) {
            System.out.println("잘못된 형변환입니다.");
        } catch (Exception e) {
            System.out.println("그 외의 문제 원인 : " + e.getMessage());
            e.printStackTrace();
        }

or를 통해서 두개의 예외를 합칠 수 있다

throw

  • 강제로 예외를 발생시키기 위한 키워드
  • 예외는 클래스이다
  • throw new 예외 클래스명(); --> 강제 에외 객체 생성 방법
  • 객체를 만들고 예외처리 해야한다
int age = 18;
        try {
            if (age < 19) {
                throw new Exception("만 19세 미만에게는 판매하지 않습니다");
            } else {
                System.out.println("판매합니다");
            }
        } catch (Exception e) {
            System.out.println("문제 원인 : " + e.getMessage());
            e.printStackTrace();
        }

finally

  • 무조건 수행해야하는 문장
  • 에러가 발생해도, 발생하지 않아도 finally 구문이 실행
try {
            System.out.println("가게 문을 연다");
            throw new Exception("오늘은 휴무");
        } catch (Exception e) {
            System.out.println("문제 원인 : " + e.getMessage());
            e.printStackTrace();
        } finally {
            System.out.println("가게 문을 닫는다");
        }

try 만 단독사용 불가능

 try {
            System.out.println(3 / 0);
        } finally {
            System.out.println("프로그램 종료");
        }

사용자 정의 예외

  • 사용자가 직접 예외 클래스를 만들 수 있다
  • Exception를 상속받아 객체를 생성
    class 예외클라스 extends Exception {
    public 예외 클래스 이ㅡㅁ(String message);
    super(messga)
    }
    이렇게 만든 사용자 정의 예외는 자바는 모르기 때문에

e.getMessage() --> 예외 객체로 부터 예외 메세지를 갖고옴
e.printStackTrace --> 예외가 발생한 위치를 추적해 가면서 예외가 발생한 클래스명 행번호등 출력

class AgeLessThan19Exception extends Exception {
    public AgeLessThan19Exception(String message) {
        super(message);
    }
}

public class _06_CustomException {
    public static void main(String[] args) {
        // 사용자 정의 예외
        int age = 18;
        try {
            if (age < 19) {
                throw new AgeLessThan19Exception("만 19세 미만에게는 판매하지 않습니다");
            } else {
                System.out.println("판매합니다");
            }
        } catch (AgeLessThan19Exception e) {
            System.out.println("성인이 되어서 와라");
        } catch (Exception e) {
            System.out.println("모든 예외 처리");
        }
        System.out.println("프로그램 정상 종료");
        System.out.println("----------------");
    }
}

예외처리 미루기 throws

  • 어떤 메소드안에서 예외가 발생이 될때 그 예외를 메소드 호출하는 쪽으로 전파하기 위한 키워드
public class _07_Throws {
    public static void main(String[] args) {
        // 예외처리 미루기
        try {
            writeFile();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("main 메소드에서 해결");
        }
    }
    
    
    // 메소드 내에서 처리하다가 발생한 문제를 내부적으로 처리하지 않고 다른데로 던진다.
    public static void writeFile() throws IOException {
        /*try {
            FileWriter writer = new FileWriter("test.txt");
            throw new IOException("파일 쓰기 실패");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("writeFile 메소드 내에서 자체 해결했어요");
        }*/

        FileWriter writer = new FileWriter("test.txt");
        throw new IOException("파일 쓰기 실패");
    }
}

RuntimeExcetion

  • 자바는 일반적으로 일어날 수 있는 예외에 대하여 이미 클래스로 만들어져 있고 자동으로 예외객체 생성
  • 예외 클래스들 중 RuntimeExcetion의 후손들은 사용자가 예외처리를 하지 않아도 자동으로 예외처리
  • RuntimeExcetion으 후손이 아닌경우 반드시 예외처리해야 한다
  • 예외처리 하지않으면 컴파일이 되지 않는다
    입출력 클래스들 = java,io 패키지
    네트워크 관련 클래스 = jave.net 패키지
    * 데이터베이스 연결 관련 클래스들 = java.sql 패키지의
    대부분의 생성자 및 메소드들은 예외를 갖고 있고 RuntimeExcetion의 후손이 아니다

참고
나도코딩 유튜브

0개의 댓글