개발 공부/[java]

예외(Exception)

죽밥죽밥화이팅 2024. 8. 7. 22:31

예외(Exception)

정상적이지 않은 Case

-0으로 나누기

-배열의 인덱스초과

-없는 파일 열기 등..

 

ex) int a = 1/0;

 

 

예외 처리(Exception Handling)

정상적이지 않은 Case에 대한 적절한 처리 방법

 

 

 

finally

예외 발생 여부와 관계없이 항상 실행되는 부분

 

 

throw, throws

throw: 예외를 강제적으로 발생 시킴

throws: 예외를 전가 시킴

 

 

package Java_14.src;// Java 프로그래밍 - 예외 처리

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

//사용자 정의 Exception
class NotTenException extends RuntimeException {}

public class Main {

    public static boolean checkTen(int ten) {
        if (ten != 10) {
            return false;
        }

        return true;
    }

    //throw -> 예외를 처리
    public static boolean checkTenWithException(int ten) {
        try {
            if (ten != 10) {
                throw new NotTenException();
            }
        } catch (NotTenException e) {
            System.out.println("e = " + e);
            return false;
        }


        if (ten != 10) {
            throw new NotTenException();
        }

        return true;
    }
    //throws
    public static boolean checkTenWithThrows(int ten) throws NotTenException {
        if (ten != 10) {
            throw new NotTenException();
        }

        return true;
    }

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

//      1. 예외
//      1-1. 0으로 나누기
        System.out.println("== 0으로 나누기 ==");
//      int a = 5 / 0;
        try {
            int a = 5 / 0;
        } catch (ArithmeticException e) {
            System.out.println("0으로 나누기 예외 발생");
            System.out.println("e = " + e);
            //e = java.lang.ArithmeticException: / by zero
        } finally { //예외가 발생하든 안하든 실행됨
            System.out.println("1-1 연습 종료");
        }


//      1-2. 배열 인덱스 초과
        System.out.println("== 배열 인덱스 초과 ==");
        int[] b = new int[4];
//        b[4] = 1;
        try {
            b[4] = 1;
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("e = " + e);
            //e = java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4
        }

        
//      1-3. 없는 파일 열기 (수업에서는 생략)
        System.out.println("== 없는 파일 열기 ==");
//        BufferedReader br = new BufferedReader(new FileReader("abc.txt"));


//      2. throw, throws
        System.out.println("== checkTen ==");
        boolean checkResult = Main.checkTen(10);
        System.out.println("checkResult = " + checkResult); //checkResult = true

        //throw -> 예외를 처리
        System.out.println("== checkTenWithException ==");
        checkResult = Main.checkTenWithException(9); //e = Java_14.src.NotTenException
        System.out.println("checkResult = " + checkResult); //checkResult = false

        //throws -> 예외를 처리하지 않고 전가
        System.out.println("== checkTenWithThrows ==");
        try {
            checkResult = checkTenWithThrows(5);
        } catch (NotTenException e) {
            System.out.println("e = " + e); //e = Java_14.src.NotTenException
        }
        System.out.println("checkResult = " + checkResult); //checkResult = false
    }

}