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:
Mệnh đề if-else trong java
Java Program to Implement Lloyd’s Algorithm
Quản lý bộ nhớ trong Java với Heap Space vs Stack
Ép kiểu trong Java (Type casting)
Spring Security and OpenID Connect
Marker Interface trong Java
Giới thiệu Java 8
How to use the Spring FactoryBean?
Hướng dẫn Java Design Pattern – Transfer Object
Java Program to Construct a Random Graph by the Method of Random Edge Selection
Login For a Spring Web App – Error Handling and Localization
Java Program to Implement Variable length array
Remove All Occurrences of a Specific Value from a List
How to Change the Default Port in Spring Boot
Hướng dẫn sử dụng Lớp FilePermission trong java
A Guide to EnumMap
Java Program to Implement Rope
Java Program to Implement HashSet API
A Guide to the Java LinkedList
Java Program to Represent Graph Using Incidence List
Java Program to Implement Find all Forward Edges in a Graph
Spring Boot - Actuator
Spring REST API + OAuth2 + Angular
Introduction to the Java ArrayDeque
Validate email address exists or not by Java Code
A Guide to the ViewResolver in Spring MVC
Java Program to Implement Graph Coloring Algorithm
Java Program to Find Path Between Two Nodes in a Graph
Guide to the Java TransferQueue
Java Program to Perform Polygon Containment Test
Java Program to Implement ArrayBlockingQueue API
Encode a String to UTF-8 in Java