Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

Java에서 메소드 재정의와 관련된 예외 처리 규칙은 무엇입니까?

<시간/>

슈퍼클래스 메서드가 재정의하는 동안 예외가 발생하는 동안 특정 규칙을 따라야 합니다.

동일한 예외 또는 하위 유형 발생

상위 클래스 메서드가 특정 예외를 throw하는 경우 하위 클래스의 메서드는 동일한 예외 또는 해당 하위 유형을 throw해야 합니다.

예시

다음 예에서 상위 클래스의 readFile() 메서드는 IOEXception을 throw하고 하위 클래스의 readFile() 메서드는 FileNotFoundException 예외를 throw합니다.

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");
      }
   }
}

출력

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.

예시

같은 방식으로 하위 클래스가 상위 클래스와 동일한 예외를 throw하면 프로그램이 성공적으로 컴파일되고 실행됩니다.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
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

수퍼 유형의 예외를 발생시키지 않아야 함

상위 클래스 메서드가 특정 예외를 throw하는 경우 하위 클래스의 메서드는 상위 유형을 throw하지 않아야 합니다.

예시

다음 예에서 상위 클래스의 readFile() 메서드는 FileNotFoundException 예외를 발생시키고, 하위 클래스의 readFile() 메서드는 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 FileNotFoundException {
      throw new FileNotFoundException();
   }
}
public class ExceptionsExample extends Super {
   @Override
   public String readFile(String path)throws IOException {
      //method body ......
   }
}

컴파일 시간 오류

컴파일할 때 위의 프로그램은 다음과 같은 출력을 제공합니다. -

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

예외 없이

상위 클래스 메서드가 특정 예외를 throw하는 경우 예외를 throw하지 않고 이를 재정의할 수 있습니다.

예시

다음 예제에서 수퍼 클래스의 sampleMethod() 메서드는 FileNotFoundException 예외를 throw하고 sampleMethod() 메서드는 예외를 전혀 throw하지 않습니다. 그래도 이 프로그램은 오류 없이 컴파일되고 실행됩니다.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
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