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:
Java Program to Implement Bloom Filter
Spring REST with a Zuul Proxy
Changing Annotation Parameters At Runtime
Hướng dẫn Java Design Pattern – Template Method
What is a POJO Class?
An Intro to Spring Cloud Task
Câu lệnh điều khiển vòng lặp trong Java (break, continue)
Spring Boot - File Handling
How to Store Duplicate Keys in a Map in Java?
Java Program to Implement Queue
Java Program to Implement Ternary Tree
Java Program to Perform Searching Based on Locality of Reference
Java Program to Check if an UnDirected Graph is a Tree or Not Using DFS
Enum trong java
Create a Custom Exception in Java
Spring @RequestParam Annotation
Java Program to Generate Random Partition out of a Given Set of Numbers or Characters
Java Program to Apply DFS to Perform the Topological Sorting of a Directed Acyclic Graph
Java Program to Check Whether an Undirected Graph Contains a Eulerian Cycle
Map to String Conversion in Java
Java Program to Find the GCD and LCM of two Numbers
Lập trình đa luồng với CompletableFuture trong Java 8
Converting between an Array and a List in Java
Function trong Java 8
Mapping Nested Values with Jackson
Debug a JavaMail Program
Java Program to Implement Wagner and Fisher Algorithm for online String Matching
Hướng dẫn Java Design Pattern – Iterator
Java Program to Perform Partition of an Integer in All Possible Ways
Creating Docker Images with Spring Boot
Hướng dẫn sử dụng luồng vào ra nhị phân trong Java
Java – Get Random Item/Element From a List