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:
The SpringJUnitConfig and SpringJUnitWebConfig Annotations in Spring 5
Java Program to add two large numbers using Linked List
Converting Between a List and a Set in Java
Java Program to Generate a Sequence of N Characters for a Given Specific Case
Java Program to Implement Booth Algorithm
Spring Boot Tutorial – Bootstrap a Simple Application
Một số tính năng mới về xử lý ngoại lệ trong Java 7
Introduction to Spring Cloud Netflix – Eureka
Apache Commons Collections BidiMap
Runnable vs. Callable in Java
Hướng dẫn Java Design Pattern – Interpreter
Java Program to Implement Bucket Sort
Tránh lỗi NullPointerException trong Java như thế nào?
Java Program to Find Hamiltonian Cycle in an UnWeighted Graph
Java Program to Find the Connected Components of an UnDirected Graph
Jackson – Bidirectional Relationships
Guide to Spring @Autowired
Spring WebClient Filters
The “final” Keyword in Java
Hướng dẫn Java Design Pattern – Bridge
Shuffling Collections In Java
Spring Boot - Tracing Micro Service Logs
Remove the First Element from a List
Connect through a Proxy
Constructor Injection in Spring with Lombok
Send an email using the SMTP protocol
So sánh Array và ArrayList trong Java
Guide to the Java TransferQueue
Java Program to Implement Attribute API
Java Program to Implement Fenwick Tree
Java Program to Implement TreeSet API
Xử lý ngoại lệ đối với trường hợp ghi đè phương thức trong java