Custom Exception trong Java

Custom Exception là ngoại lệ do người dùng tự định nghĩa. Custom Exception trong Java được sử dụng để tùy biến ngoại lệ theo yêu cầu của người dùng. Bởi sự giúp đỡ của loại ngoại lệ này, người dùng có thể có riêng kiểu và thông điệp ngoại lệ riêng cho mình.

Thông thường, để tạo ra custom exception thuộc loại checked chúng ta kế thừa từ lớp Exception. Để tạo custom exception thuộc loại unchecked chúng ta kế thừa từ lớp RuntimeException.

Trong các ứng dụng thực tế, thông thường custom exception được tạo là checked exception.

Ví dụ:

Tạo ngoại lệ tùy chỉnh thuộc loại checked exception:

class InvalidAgeException extends Exception {
    InvalidAgeException(String s) {
        super(s);
    }
}

Sử dụng ngoại lệ tùy chỉnh:

class CustomExceptionExample {
 
    static void validate(int age) throws InvalidAgeException {
        if (age < 18) {
            throw new InvalidAgeException("not valid");
        } else {
            System.out.println("welcome to vote");
        }
    }
 
    public static void main(String args[]) {
        try {
            validate(13);
        } catch (Exception m) {
            System.out.println("Exception occured: " + m);
        }
 
        System.out.println("rest of the code...");
    }
}

Kết quả thực thi chương trình trên:

Exception occured: com.maixuanviet.throwex.InvalidAgeException: not valid
rest of the code...


Related posts:

Các chương trình minh họa sử dụng Cấu trúc điều khiển trong Java
Hướng dẫn Java Design Pattern – Bridge
Java Web Services – Jersey JAX-RS – REST và sử dụng REST API testing tools với Postman
Java Program to Check whether Graph is a Bipartite using BFS
Model, ModelMap, and ModelAndView in Spring MVC
Form Validation with AngularJS and Spring MVC
Write/Read cookies using HTTP and Read a file from the internet
Hamcrest Collections Cookbook
A Guide to Spring Cloud Netflix – Hystrix
Giới thiệu java.io.tmpdir
Java Program to Compute Discrete Fourier Transform Using the Fast Fourier Transform Approach
Iterable to Stream in Java
Spring MVC and the @ModelAttribute Annotation
Converting a Stack Trace to a String in Java
Loại bỏ các phần tử trùng trong một ArrayList như thế nào?
Java Program to Implement Cartesian Tree
Java Program to Find the Edge Connectivity of a Graph
Overview of the java.util.concurrent
Getting a File’s Mime Type in Java
Compact Strings in Java 9
Sử dụng JDBC API thực thi câu lệnh truy vấn dữ liệu
Introduction to Netflix Archaius with Spring Cloud
Guide to the Java TransferQueue
Biểu thức Lambda trong Java 8 – Lambda Expressions
Spring Cloud Series – The Gateway Pattern
Java Program to Implement Dijkstra’s Algorithm using Set
Error Handling for REST with Spring
Getting the Size of an Iterable in Java
Hướng dẫn sử dụng Java Annotation
Java Program to Implement Stack
Introduction to Using Thymeleaf in Spring
Quick Guide to Spring Controllers