Xử lý ngoại lệ đối với trường hợp ghi đè phương thức trong java

Có một vài quy tắc về xử lý ngoại lệ (exception handling) với ghi đè (overriding) phương thức trong java như sau:

1. Trường hợp phương thức của lớp cha không khai báo ném ra exception

Nếu phương thức của lớp cha không khai báo ném ra exception, phương thức được ghi đè của lớp cha không thể khai báo ném ra ngoại lệ checked, nhưng ngoại lệ unchecked thì có thể.

1.1. Ví dụ lớp con không thể khai báo ném ra ngoại lệ checked

class Parent {
    void msg() {
        System.out.println("parent");
    }
}
import java.io.IOException;
 
public class ExceptionChildExample extends Parent {
    void msg() throws IOException { // không thể khai báo ném ra ngoại lệ checked
        System.out.println("TestExceptionChild");
    }
 
    public static void main(String args[]) {
        Parent p = new ExceptionChildExample();
        p.msg();
    }
}

Thực thi chương trình trên:

Compile Time Error

1.2. Ví dụ lớp con có thể khai báo ném ra ngoại lệ unchecked

class Parent {
    void msg() {
        System.out.println("parent");
    }
}
public class ExceptionChildExample extends Parent {
    void msg() throws ArithmeticException { // có thể khai báo ném ra ngoại lệ unchecked
        System.out.println("TestExceptionChild");
    }
 
    public static void main(String args[]) {
        Parent p = new ExceptionChildExample();
        p.msg();
    }
}

Thực thi chương trình trên:

TestExceptionChild

2. Trường hợp phương thức của lớp cha khai báo ném ra exception

Nếu phương thức của lớp cha khai báo ném ra exception, phương thức được ghi đè của lớp cha có thể khai báo ném ra ngoại lệ tương tự, ngoại lệ con, nhưng không thể khai báo ném ra ngoại lệ cha.

2.1. Ví dụ phương thức ghi đè của lớp cha khai báo ném ra ngoại lệ cha

class Parent {
    void msg() throws ArithmeticException {
        System.out.println("parent");
    }
}
public class ExceptionChildExample extends Parent {
    // Exception Exception is not compatible with throws clause in Parent.msg()
    void msg() throws Exception { // Không thể khai báo ném ra ngoại lệ cha
        System.out.println("child");
    }
 
    public static void main(String args[]) {
        Parent p = new ExceptionChildExample();
        try {
            p.msg();
        } catch (Exception e) {
        }
    }
}

Thực thi chương trình trên:

Compile Time Error

2.2. Ví dụ phương thức ghi đè của lớp cha khai báo ném ra ngoại lệ tương tự

class Parent {
    void msg() throws Exception {
        System.out.println("parent");
    }
}
public class ExceptionChildExample extends Parent {
    void msg() throws Exception {
        System.out.println("child");
    }
 
    public static void main(String args[]) {
        Parent p = new ExceptionChildExample();
        try {
            p.msg();
        } catch (Exception e) {
        }
    }
}

Thực thi chương trình trên:

child

2.3. Ví dụ phương thức ghi đè của lớp cha khai báo ném ra ngoại lệ con

class Parent {
    void msg() throws Exception {
        System.out.println("parent");
    }
}
public class ExceptionChildExample extends Parent {
    void msg() throws ArithmeticException {
        System.out.println("child");
    }
 
    public static void main(String args[]) {
        Parent p = new ExceptionChildExample();
        try {
            p.msg();
        } catch (Exception e) {
        }
    }
}

Thực thi chương trình trên:

child

2.4. Ví dụ phương thức ghi đè của lớp cha không khai báo ném ra ngoại lệ nào

class Parent {
    void msg() throws Exception {
        System.out.println("parent");
    }
}
public class ExceptionChildExample extends Parent {
    void msg() {
        System.out.println("child");
    }
 
    public static void main(String args[]) {
        Parent p = new ExceptionChildExample();
        try {
            p.msg();
        } catch (Exception e) {
        }
    }
}

Thực thi chương trình trên:

child

Related posts:

Limiting Query Results with JPA and Spring Data JPA
Inheritance with Jackson
A Guide to Queries in Spring Data MongoDB
Convert XML to JSON Using Jackson
Hướng dẫn sử dụng lớp Console trong java
Introduction to Using Thymeleaf in Spring
Tính đa hình (Polymorphism) trong Java
Java Program to Check Whether a Given Point is in a Given Polygon
Spring Security Login Page with React
Java Program for Douglas-Peucker Algorithm Implementation
Biểu thức Lambda trong Java 8 – Lambda Expressions
New Features in Java 10
Java Program to Find Minimum Element in an Array using Linear Search
Java Program for Topological Sorting in Graphs
Java Program to Check whether Undirected Graph is Connected using DFS
Java Program to Implement First Fit Decreasing for 1-D Objects and M Bins
Getting Started with Stream Processing with Spring Cloud Data Flow
Bootstrap a Web Application with Spring 5
Spring Data Java 8 Support
Java – Convert File to InputStream
Chuyển đổi Array sang ArrayList và ngược lại
Java Program to Perform Partial Key Search in a K-D Tree
Giới thiệu Swagger – Công cụ document cho RESTfull APIs
Cachable Static Assets with Spring MVC
Java Program to Implement Stack using Two Queues
Java Program to Implement Double Order Traversal of a Binary Tree
Java Program to Perform Polygon Containment Test
Spring Boot: Customize the Jackson ObjectMapper
4 tính chất của lập trình hướng đối tượng trong Java
Java Program to Find Location of a Point Placed in Three Dimensions Using K-D Trees
Ép kiểu trong Java (Type casting)
Java Program to Implement Variable length array