>  기사  >  Java  >  Java의 메소드 적용 범위 및 예외 처리에 대한 규칙은 무엇입니까?

Java의 메소드 적용 범위 및 예외 처리에 대한 규칙은 무엇입니까?

WBOY
WBOY앞으로
2023-09-06 18:29:13622검색

Java의 메소드 적용 범위 및 예외 처리에 대한 규칙은 무엇입니까?

슈퍼클래스 메서드를 재정의할 때 메서드에서 예외가 발생하면 특정 규칙을 따라야 합니다.

동일한 예외 또는 하위 유형을 발생시켜야 합니다.

수퍼클래스 메서드가 특정 예외를 발생시키는 경우 하위 클래스의 메서드도 동일한 예외 또는 해당 하위 유형을 발생시켜야 합니다.

Example

다음 예에서 슈퍼클래스의 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");
      }
   }
}

Output

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.

Example

마찬가지로 하위 클래스가 상위 클래스와 동일한 예외를 발생시키면 프로그램이 성공적으로 컴파일되고 실행됩니다.

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

Output

Method of Subclass

슈퍼클래스 예외를 발생시키지 않아야 합니다.

슈퍼클래스 메서드가 예외를 발생시키는 경우 하위 클래스의 메서드는 해당 슈퍼클래스를 발생시켜서는 안 됩니다.

Example

다음 예에서 슈퍼클래스의 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

예외를 발생시키지 않습니다.

부모 클래스 메서드에서 예외가 발생하는 경우 예외를 발생시키지 않고 이를 재정의할 수 있습니다.

Example

아래 예에서 상위 클래스의 SampleMethod() 메서드는 FileNotFoundException 예외를 발생시키는 반면, 하위 클래스의 SampleMethod() 메서드는 전혀 예외를 발생시키지 않습니다. 그럼에도 불구하고 프로그램은 오류 없이 컴파일되고 실행됩니다.

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

위 내용은 Java의 메소드 적용 범위 및 예외 처리에 대한 규칙은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 tutorialspoint.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제
이전 기사:Java의 Jar 파일다음 기사:Java의 Jar 파일