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:
ClassNotFoundException vs NoClassDefFoundError
OAuth2 for a Spring REST API – Handle the Refresh Token in Angular
How to Return 404 with Spring WebFlux
Using Java Assertions
Merging Two Maps with Java 8
Java Program to Check if a Given Graph Contain Hamiltonian Cycle or Not
Spring Data MongoDB Transactions
Java Program to Implement Traveling Salesman Problem using Nearest neighbour Algorithm
Java Program to Implement String Matching Using Vectors
Java Program to Implement Flood Fill Algorithm
Easy Ways to Write a Java InputStream to an OutputStream
CyclicBarrier in Java
Java Map With Case-Insensitive Keys
Java Program to Implement Affine Cipher
Guide to Spring @Autowired
Lớp Properties trong java
Java Program to Implement Branch and Bound Method to Perform a Combinatorial Search
Introduction to Spliterator in Java
An Intro to Spring Cloud Contract
Java Program to Implement Fermat Primality Test Algorithm
Stack Memory and Heap Space in Java
MyBatis with Spring
Java Program to Implement Kosaraju Algorithm
Introduction to Spring Data JDBC
Removing all Nulls from a List in Java
Spring Boot - Enabling HTTPS
Hướng dẫn Java Design Pattern – Abstract Factory
Guide To CompletableFuture
Guide to Mustache with Spring Boot
Rate Limiting in Spring Cloud Netflix Zuul
Guide to CopyOnWriteArrayList
Java Program to Implement Borwein Algorithm