Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Quy tắc override method ném exception trong Java

Khi override phương thức ném exception, cần tuân thủ các quy tắc sau:

Quy tắc 1: Parent method không ném exception

  • Child method KHÔNG ĐƯỢC ném checked exception.
  • Child method CÓ THỂ ném unchecked exception (RuntimeException).
class Parent { 
    void doSomething() { /* ... */ } 
} 
class Child extends Parent { 
    void doSomething() throws IllegalArgumentException { /* ... */ } // OK - unchecked 
}

Quy tắc 2: Parent method ném checked exception

  • Child method có thể ném cùng exception.
  • Child method có thể ném subclass của exception đó.
  • Child method có thể ném ít exception hơn (subset).
  • Child method KHÔNG ĐƯỢC ném exception cha (superclass) hoặc exception không liên quan.
  • Child method LUÔN CÓ THỂ ném unchecked exception.
class Parent { 
    void doSomething() throws IOException, ParseException { /* ... */ } 
    void doSomethingElse() throws IOException { /* ... */ } 
} 
class Child extends Parent { 
    void doSomething() throws IOException { /* ... */ } // OK - subset 
    void doSomethingElse() throws FileNotFoundException, EOFException { /* ... */ } // OK - subclass of IOException 
}

Quy tắc 3: Parent method ném unchecked exception

  • Child method có thể ném bất kỳ unchecked exception nào (dù không liên quan).
  • Child method có thể không ném exception nào.
class Parent { 
    void doSomething() throws IllegalArgumentException { /* ... */ } 
} 
class Child extends Parent { 
    void doSomething() throws ArithmeticException, BufferOverflowException { /* ... */ } // OK - unchecked bất kỳ 
}

Ví dụ hoàn chỉnh

import java.io.*; 

class SuperClassTest { 
    public void test() throws IOException { 
        System.out.println("SuperClassTest.test() method"); 
    } 
} 

class SubClassTest extends SuperClassTest { 
    public void test() { // Không ném exception - OK 
        System.out.println("SubClassTest.test() method"); 
    } 
} 

public class OverridingExceptionTest { 
    public static void main(String[] args) { 
        SuperClassTest sct = new SubClassTest(); 
        try { 
            sct.test(); 
        } catch(IOException ioe) { 
            ioe.printStackTrace(); 
        } 
    } 
}

Kết quả

SubClassTest.test() method

Tóm tắt quy tắc (Liskov Substitution Principle cho Exception)

Parent throwsChild throws đượcChild throws KHÔNG được
RỗngUnchecked (RuntimeException)Checked exception
Checked (IOException)Cùng loại, subclass, subset, uncheckedSuperclass (Exception), unrelated checked
Unchecked (IllegalArgumentException)Bất kỳ unchecked, rỗngChecked exception