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:
Custom Thread Pools In Java 8 Parallel Streams
Compact Strings in Java 9
How to Manually Authenticate User with Spring Security
Tránh lỗi NullPointerException trong Java như thế nào?
Java Program to Implement Graph Structured Stack
Java Program to Generate All Possible Combinations Out of a, b, c, d, e
Java Web Services – Jersey JAX-RS – REST và sử dụng REST API testing tools với Postman
A Guide to WatchService in Java NIO2
A Guide to the ResourceBundle
Introduction to Spliterator in Java
JPA/Hibernate Persistence Context
Tạo ứng dụng Java RESTful Client với thư viện Retrofit
Tính trừu tượng (Abstraction) trong Java
Java Program to Represent Graph Using Incidence Matrix
Chuyển đổi giữa các kiểu dữ liệu trong Java
Lớp Collections trong Java (Collections Utility Class)
Check If Two Lists are Equal in Java
Java Program to Find MST (Minimum Spanning Tree) using Kruskal’s Algorithm
Java Program to Check the Connectivity of Graph Using BFS
Java Program to Find the Minimum Element of a Rotated Sorted Array using Binary Search approach
New Features in Java 13
Inheritance with Jackson
Prevent Brute Force Authentication Attempts with Spring Security
Introduction to Eclipse Collections
Spring Security Logout
Java Program to Perform Matrix Multiplication
Guide to @ConfigurationProperties in Spring Boot
Java Program to Generate All Subsets of a Given Set in the Gray Code Order
Java 14 Record Keyword
Guide to Spring 5 WebFlux
Java Program to Perform Polygon Containment Test
Java Convenience Factory Methods for Collections