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 Find the Nearest Neighbor Using K-D Tree Search
Java Program to Implement Jarvis Algorithm
Hướng dẫn Java Design Pattern – Decorator
Service Registration with Eureka
Java Program to Implement Max Heap
Convert Character Array to String in Java
HttpClient Connection Management
Queue và PriorityQueue trong Java
Java Program to Implement Floyd-Warshall Algorithm
Explain about URL and HTTPS protocol
Java Program to Implement PrinterStateReasons API
Adding a Newline Character to a String in Java
The HttpMediaTypeNotAcceptableException in Spring MVC
Kết hợp Java Reflection và Java Annotations
Tạo ứng dụng Java RESTful Client với thư viện OkHttp
Using JWT with Spring Security OAuth
Java 8 Stream findFirst() vs. findAny()
REST Web service: Upload và Download file với Jersey 2.x
Iterating over Enum Values in Java
Intro to Spring Boot Starters
How to Store Duplicate Keys in a Map in Java?
Java Program to Represent Linear Equations in Matrix Form
HttpClient 4 Cookbook
Control Structures in Java
Spring Boot - Exception Handling
Converting String to Stream of chars
Java Program to Implement Disjoint Sets
Spring Boot Annotations
Serialize Only Fields that meet a Custom Criteria with Jackson
Java Program to Perform Sorting Using B-Tree
Java – Get Random Item/Element From a List
Java Program to Implement Interval Tree