JAVA/기초공부

[JAVA] 예외처리

SoU330 2024. 10. 13. 01:02

 

 

 

프로그래을 실행하는 도중에 논리적인 오류나 예기치 못한 시스템 오류들을 접하게 된다.

 

시스템 오류  - 갑자기 수행을 멈추거나 디스크오류 등의 시스템과 관련된 오류로서 해결이 불가능하다.

논리적 오류 - 구문적으로는 올바르지만 개발자가 의도한 대로 동작하지 않는 경우

비정상적인 오류(Exception) - 시스템 오류나 논리적 오류가 아닌 오류

비정상적인 예외인 경우 프로그램에서 오류를 미리 예측하고 대비하여 적절한 처리를 한 다음 프로그램 수행을 계속하여 정상적인 종료가 되도록 한다.(exception handling)

 

 

 

 

 

예외처리 종류

Array Index Out Of Bounds Exception 배열의 크기를 초과하여 인덱스 지정한 경우
ArithmeticException 나눗셈에서 0으로 나눈 경우 발생
IOException 입출력 관련된 오류인 경우 발생
NegativeArraySizeException 배열의 크기를 음수로 지정한 경우 발생
NullPointerException 참조할 객체가 없는 경우 발생
NoSuchMethodException 메소드를 찾을 수 없는 경우 발생

 

 

 

 

 

예외처리 방법

  • try ~ catch (~ finally ) : 시스템에서 발생하는 예외 상황을 사전에 탐지하여 적절하게 예외 처리를 해주는 방법
  • throw : 실행 중 예외가 발생하면 예외처리를 시스템에게 넘겨 주는 방법

 

 

 

try-catch-finally 에 의한 예외처리

try 블록 : 예외가 발생할 수 있는 코드를 작성하는 곳

catch 블록 : try 블록에서 예외가 발생하면 해당 예외를 처리하는 코드가 실행되는 곳

finally 블록 (선택 사항) : 예외 발생 여부와 상관없이 반드시 실행되는 코드. 보통 자원 해제에 사용(파일 닫기, 데이터베이스 연결 종료)

 

 

 

 

 

try~catch 사용 전 예러가 난 경우

System.out.print("분자 입력 : ");
numer = sc.nextInt();
System.out.print("분모 입력 : ");
denom = sc.nextInt();
result = numer / denom; // 나눗셈에서 분모가 0인 경우 주의
System.out.printf("%d / %d = %d",numer,denom,result);

 

-> 분모를 0으로 입력했을 때 이런 오류가 발생한다.

 

 

 

try~catch 사용 예 

try {
    int numer, denom, result;
    System.out.print("분자 입력 : ");
    numer = sc.nextInt();
    System.out.print("분모 입력 : ");
    denom = sc.nextInt();
    result = numer / denom; // 나눗셈에서 분모가 0인 경우
    // DivideByZeroException 오류 발생
    System.out.printf("%d / %d = %d",numer,denom,result);
}
catch (ArithmeticException de) { // 분모가 0인 경우
    System.out.println("분자를 0으로 나누려 함");
    System.out.println("Message : " + de.getMessage());
    de.printStackTrace();
}
catch (Exception fe) { // 분자 또는 분모가 숫자가 아닌 경우
    System.out.println("정수가 아닌 값을 입력함");
    System.out.println("Message : " + fe.getMessage());
    fe.printStackTrace();
}
finally { // 이 문장은 반드시 수행
    System.out.println("finally 문장은 반드시 수행");
}

-> catch 블록을 사용해 각각의 예외를 처리할 수 있다. finally 블록은 반드시 수행한다.

 

 

 

 

throw와 throws 문에 의한 예외처리

thow

  • 직접 예외를 발생시킬 때 사용
  • 특정 조건에서 예외가 발생해야 한다고 판단될 때 개발자가 직접 예외를 던질 수 있다.
public class ThrowExample {
    public static void validateAge(int age) {
        if (age < 18) {
            throw new IllegalArgumentException("나이는 18세 이상이어야 합니다.");
        }
    }

    public static void main(String[] args) {
        try {
            validateAge(15); // 18세 미만이므로 예외 발생
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }
}

 

 

 

 

throws

  • 메소드 선언부에서 사용
  • 예외를 던질 수 있음을 알리는 역할
  • 메소드를 호출한 곳에서 예외를 처리하도록 책임을 넘길 수 있다.
public class ThrowsExample {
    // 파일을 읽는 메소드에서 예외가 발생할 수 있으므로 throws로 선언
    public static void readFile(String filePath) throws IOException {
        FileReader file = new FileReader(filePath);
        BufferedReader reader = new BufferedReader(file);
        System.out.println(reader.readLine());
        reader.close();
    }

    public static void main(String[] args) {
        try {
            // readFile 메소드를 호출하면서 발생 가능한 예외 처리
            readFile("test.txt");
        } catch (IOException e) {
            System.out.println("파일을 읽는 도중 예외 발생: " + e.getMessage());
        }
    }
}

 

 

 

 

 

 

 

사용자 정의 예외 클래스

: 개발자가 직접 필요에 따라 정의한 예외

  • Exception 클래스를 상속 받아 사용자가 임의로 예외 클래스를 정의하여 사용할 수 있다.
  • 특정 상황에서 발생할 수 있는 예외를 더 구체적으로 표현하거나, 보다 의미 있는 예외 메시지를 제공하기 위해 사용자 정의 예외를 만들 수 있다.

 

 

 

 

사용자 정의 예외처리를 사용한 경우

1~3 외의 수를 입력받았을 때 예외처리 제작

public class UserMakeException extends Exception{
    private static final long serialVersionUID = 1L;
    public UserMakeException() {
        super("\n번호 선택하세요. 1~3 입니다.");
    }
}

 

테스트코드

public static int inputNumber() throws Exception, UserMakeException {
    System.out.print("번호 선택하세요. [1~3] : ");
    int n = sc.nextInt();
    try {
        if (n < 1 || n > 3) {
            throw new UserMakeException();
        }
    } catch (Exception e) {
        throw e;
    }
    return n;
}

-> throws와 throw를 이용해서 해당 에러라는 것을 알림