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 Solve a Matching Problem for a Given Specific Case
Java Program to Implement Best-First Search
A Guide to JUnit 5
Constructor Injection in Spring with Lombok
Java Program to Implement Gaussian Elimination Algorithm
Spring Boot - Thymeleaf
Java Program to Find the GCD and LCM of two Numbers
Hướng dẫn Java Design Pattern – Intercepting Filter
Tránh lỗi NullPointerException trong Java như thế nào?
Jackson – JsonMappingException (No serializer found for class)
Use Liquibase to Safely Evolve Your Database Schema
Java Convenience Factory Methods for Collections
Guide to WeakHashMap in Java
Spring Boot With H2 Database
Java – Reader to InputStream
Java Program to Implement Binary Heap
Java Program to Perform integer Partition for a Specific Case
Java Program to Implement Quick sort
Zipping Collections in Java
Java Program to Implement a Binary Search Tree using Linked Lists
So sánh HashMap và HashSet trong Java
HttpClient 4 – Send Custom Cookie
File Upload with Spring MVC
A Guide to Java 9 Modularity
Java Program to Perform Naive String Matching
New in Spring Security OAuth2 – Verify Claims
Tính đóng gói (Encapsulation) trong java
Java Program to Implement Multi-Threaded Version of Binary Search Tree
Debugging Reactive Streams in Java
So sánh HashMap và Hashtable trong Java
Java TreeMap vs HashMap
Java Program to Implement Threaded Binary Tree