인터뷰 질문을하겠습니다. 슈퍼 클래스에서 NullPointerException을 발생시키는 메서드가 있습니다. RuntimeException을 발생시키는 메소드로 재정의 할 수 있습니까?
이 질문에 답하려면 Unchecked 및 Checked 예외가 무엇인지 알려주십시오.
확인 된 예외는 기본 try-catch-finally 예외 처리에 설명 된대로 명시 적으로 포착되거나 전파되어야합니다. 확인되지 않은 예외에는이 요구 사항이 없습니다. 그들은 잡히거나 던져 질 필요가 없습니다.
Java에서 확인 된 예외는 java.lang.Exception 클래스를 확장합니다. 확인되지 않은 예외는 java.lang.RuntimeException을 확장합니다.
공용 클래스 NullPointerException은 RuntimeException을 확장합니다.
확인되지 않은 예외는 java.lang.RuntimeException을 확장합니다. 이것이 NullPointerException이 Uncheked 예외 인 이유입니다.
예를 들어 보겠습니다. 예 1 :
public class Parent {
public void name() throws NullPointerException {
System.out.println(" this is parent");
}
}
public class Child extends Parent{
public void name() throws RuntimeException{
System.out.println(" child ");
}
public static void main(String[] args) {
Parent parent = new Child();
parent.name();// output => child
}
}
프로그램이 성공적으로 컴파일됩니다. 예 2 :
public class Parent {
public void name() throws RuntimeException {
System.out.println(" this is parent");
}
}
public class Child extends Parent{
public void name() throws NullPointerException {
System.out.println(" child ");
}
public static void main(String[] args) {
Parent parent = new Child();
parent.name();// output => child
}
}
프로그램도 성공적으로 컴파일됩니다. 따라서 확인되지 않은 예외의 경우 아무 일도 일어나지 않음이 분명합니다. 이제 Checked 예외의 경우 어떤 일이 발생하는지 살펴 보겠습니다. 예제 3 : 기본 클래스와 자식 클래스가 모두 확인 된 예외를 throw하는 경우
public class Parent {
public void name() throws IOException {
System.out.println(" this is parent");
}
}
public class Child extends Parent{
public void name() throws IOException{
System.out.println(" child ");
}
public static void main(String[] args) {
Parent parent = new Child();
try {
parent.name();// output=> child
}catch( Exception e) {
System.out.println(e);
}
}
}
프로그램이 성공적으로 컴파일됩니다. 예제 4 : 기본 클래스의 동일한 메서드와 비교하여 자식 클래스 메서드에서 테두리 확인 예외가 발생하는 경우.
import java.io.IOException;
public class Parent {
public void name() throws IOException {
System.out.println(" this is parent");
}
}
public class Child extends Parent{
public void name() throws Exception{ // broader exception
System.out.println(" child ");
}
public static void main(String[] args) {
Parent parent = new Child();
try {
parent.name();//output=> Compilation failure
}catch( Exception e) {
System.out.println(e);
}
}
}
프로그램이 컴파일되지 않습니다. 따라서 Checked 예외를 사용할 때주의해야합니다.