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 Test Using DFS Whether a Directed Graph is Strongly Connected or Not
Java Program to Perform Quick Sort on Large Number of Elements
Spring Data JPA @Query
Java Program to Implement Treap
Java Program to Implement Stack API
A Guide to Java HashMap
LinkedHashSet trong Java hoạt động như thế nào?
Spring Webflux with Kotlin
Guide to Selenium with JUnit / TestNG
Java Program to Generate Random Numbers Using Multiply with Carry Method
Java Program to Implement ArrayList API
Validations for Enum Types
Java Program to Perform Partition of an Integer in All Possible Ways
Java Program to Implement Binary Heap
Guide to ThreadLocalRandom in Java
Lớp HashMap trong Java
The Dining Philosophers Problem in Java
Unsatisfied Dependency in Spring
Jackson Exceptions – Problems and Solutions
Spring Boot - Interceptor
Java Program to Implement Bucket Sort
Java Program to Perform Deletion in a BST
Vector trong Java
Spring 5 and Servlet 4 – The PushBuilder
Java Program to Implement AA Tree
Constructor Dependency Injection in Spring
Java Program to Represent Graph Using Adjacency Matrix
Copy a List to Another List in Java
Java Program to Represent Graph Using 2D Arrays
The Modulo Operator in Java
Java Program to Perform Optimal Paranthesization Using Dynamic Programming
Spring Boot - Admin Client