Computer >> 컴퓨터 >  >> 프로그래밍 >> Java

Java 메소드 오버라이딩 시 반드시 알아야 할 예외 처리 규칙

상위 클래스(슈퍼 클래스)의 메소드가 예외를 던지도록 선언되어 있다면, 이를 재정의(오버라이딩)할 때는 반드시 몇 가지 규칙을 따라야 합니다. 이 규칙을 지키지 않으면 컴파일 오류가 발생하므로, 자바에서 상속과 예외 처리를 함께 다룰 때 정확히 이해해 두는 것이 중요합니다.

1. 동일한 예외 또는 하위 타입의 예외를 던져야 합니다

상위 클래스의 메소드가 특정 예외를 던진다면, 하위 클래스에서 재정의한 메소드는 같은 예외 또는 그 예외의 하위(자식) 타입을 던져야 합니다.

예제

다음 예제에서 상위 클래스의 readFile() 메소드는 IOException을 던지고, 하위 클래스의 readFile() 메소드는 FileNotFoundException을 던집니다.

FileNotFoundException은 IOException의 하위 타입이므로, 이 프로그램은 아무 오류 없이 정상적으로 컴파일되어 실행됩니다.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;

abstract class Super {
    public String readFile(String path) throws IOException {
        throw new IOException();
    }
}

public class ExceptionsExample extends Super {
    @Override
    public String readFile(String path) throws FileNotFoundException {
        Scanner sc = new Scanner(new File("E://test//sample.txt"));
        String input;
        StringBuffer sb = new StringBuffer();
        while (sc.hasNextLine()) {
            input = sc.nextLine();
            sb.append(" " + input);
        }
        return sb.toString();
    }

    public static void main(String args[]) {
        String path = "E://test//sample.txt";
        ExceptionsExample obj = new ExceptionsExample();
        try {
            System.out.println(obj.readFile(path));
        } catch (FileNotFoundException e) {
            System.out.println("Make sure the specified file exists");
        }
    }
}

실행 결과

프로그램을 실행하면 지정한 파일(sample.txt)의 내용이 그대로 화면에 출력됩니다.

Tutorials Point is an E-learning company that set out on its journey to provide knowledge to that class of readers that responds better to online content. With Tutorials Point, you can learn at your own pace, in your own space. After a successful journey of providing the best learning content at tutorialspoint.com, we created our subscription based premium product called Tutorix to provide Simply Easy Learning in the best personalized way for K-12 students, and aspirants of competitive exams like IIT/JEE and NEET.

동일한 예외를 던지는 경우

마찬가지로 하위 클래스가 상위 클래스와 완전히 동일한 예외를 던지는 경우에도 프로그램은 문제없이 컴파일되고 실행됩니다.

import java.io.FileNotFoundException;

abstract class Super {
    public void sampleMethod() throws FileNotFoundException {
        System.out.println("Method of superclass");
    }
}

public class ExceptionsExample extends Super {
    public void sampleMethod() throws FileNotFoundException {
        System.out.println("Method of Subclass");
    }

    public static void main(String args[]) {
        ExceptionsExample obj = new ExceptionsExample();
        obj.sampleMethod();
    }
}

실행 결과

Method of Subclass

2. 상위 타입의 예외를 던져서는 안 됩니다

상위 클래스의 메소드가 특정 예외를 던진다면, 하위 클래스의 메소드는 그보다 범위가 넓은 상위(부모) 타입의 예외를 던져서는 안 됩니다. 이는 다형성과 관련이 있는데, 상위 클래스 타입으로 객체를 다루는 호출자 입장에서 원래 메소드가 던지지 않던 새로운 예외가 갑자기 발생할 수 있기 때문입니다.

예제

다음 예제에서 상위 클래스의 readFile() 메소드는 FileNotFoundException을 던지는데, 하위 클래스의 readFile() 메소드는 FileNotFoundException의 상위 타입인 IOException을 던지도록 선언되어 있습니다.

import java.io.FileNotFoundException;
import java.io.IOException;

abstract class Super {
    public String readFile(String path) throws FileNotFoundException {
        throw new FileNotFoundException();
    }
}

public class ExceptionsExample extends Super {
    @Override
    public String readFile(String path) throws IOException {
        // 메소드 본문 ......&n    }
}

컴파일 오류

위 프로그램을 컴파일하면 다음과 같은 오류 메시지가 출력됩니다.

ExceptionsExample.java:13: error: readFile(String) in ExceptionsExample cannot override readFile(String) in Sup
    public String readFile(String path)throws IOException {
                   ^
    overridden method does not throw IOException
1 error

오류 메시지의 의미는 "재정의된 메소드는 IOException을 던질 수 없다"는 것입니다. 즉, 하위 클래스 메소드가 상위 클래스 메소드보다 넓은 범위의 예외를 던지는 것은 허용되지 않습니다.

3. 아무 예외도 던지지 않아도 됩니다

상위 클래스의 메소드가 예외를 던지더라도, 하위 클래스에서 재정의할 때 어떤 예외도 던지지 않도록 구현할 수 있습니다. 예외 범위를 줄이거나 없애는 방향은 항상 허용되기 때문입니다.

예제

다음 예제에서 상위 클래스의 sampleMethod() 메소드는 FileNotFoundException을 던지지만, 하위 클래스의 sampleMethod() 메소드는 어떤 예외도 던지지 않습니다. 그럼에도 이 프로그램은 오류 없이 정상적으로 컴파일되고 실행됩니다.

import java.io.FileNotFoundException;

abstract class Super {
    public void sampleMethod() throws FileNotFoundException {
        System.out.println("Method of superclass");
    }
}

public class ExceptionsExample extends Super {
    public void sampleMethod() {
        System.out.println("Method of Subclass");
    }

    public static void main(String args[]) {
        ExceptionsExample obj = new ExceptionsExample();
        obj.sampleMethod();
    }
}

실행 결과

Method of Subclass

규칙 요약

  • 상위 클래스 메소드가 던지는 예외와 동일한 예외를 던질 수 있습니다.
  • 그 예외의 하위 타입을 던질 수도 있습니다.
  • 상위 타입의 예외를 던지면 컴파일 오류가 발생합니다.
  • 예외를 아예 던지지 않고 재정의하는 것도 가능합니다.

핵심은 "재정의된 메소드는 원래 메소드보다 같거나 좁은 범위의 예외만 던질 수 있다"는 것입니다. 이 규칙을 지키면 상위 클래스 타입으로 객체를 사용하는 클라이언트 코드가 예상치 못한 예외로 인해 깨지는 상황을 예방할 수 있습니다.