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 – InputStream to Reader
REST Web service: Upload và Download file với Jersey 2.x
Iterable to Stream in Java
Java Program to Show the Duality Transformation of Line and Point
Spring Boot - Introduction
Java Timer
Apache Commons Collections OrderedMap
Java Program to Perform Left Rotation on a Binary Search Tree
Sorting in Java
Array to String Conversions
Functional Interfaces in Java 8
Lớp TreeMap trong Java
Các nguyên lý thiết kế hướng đối tượng – SOLID
Java Program to Apply DFS to Perform the Topological Sorting of a Directed Acyclic Graph
Getting Started with Forms in Spring MVC
Enum trong java
Java Program to Implement the RSA Algorithm
Java 8 Stream findFirst() vs. findAny()
Understanding Memory Leaks in Java
Spring Boot - Application Properties
Hướng dẫn Java Design Pattern – Decorator
Java Program to Test Using DFS Whether a Directed Graph is Weakly Connected or Not
Java Program to Implement Skip List
Java Program to Implement Hash Tables with Linear Probing
REST Pagination in Spring
Join and Split Arrays and Collections in Java
Setting the Java Version in Maven
Java Program to Implement Bucket Sort
Java Program to Implement Maximum Length Chain of Pairs
Spring Security Login Page with React
RegEx for matching Date Pattern in Java
Spring Autowiring of Generic Types