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 Describe the Representation of Graph using Adjacency Matrix
More Jackson Annotations
Quản lý bộ nhớ trong Java với Heap Space vs Stack
Vector trong Java
Jackson vs Gson
Tạo số và chuỗi ngẫu nhiên trong Java
Java Program to Implement Red Black Tree
Number Formatting in Java
The Order of Tests in JUnit
Mảng (Array) trong Java
Java Program to Implement Hopcroft Algorithm
Java Program to Check if a Given Graph Contain Hamiltonian Cycle or Not
Java Program to Implement Flood Fill Algorithm
Java Program to Implement K Way Merge Algorithm
Set Interface trong Java
So sánh ArrayList và Vector trong Java
Java Program to Implement Disjoint Set Data Structure
Compact Strings in Java 9
Java Program to Find the GCD and LCM of two Numbers
Java Program to Implement Quick Hull Algorithm to Find Convex Hull
Java Program to Solve any Linear Equation in One Variable
Java Program to Implement Graph Coloring Algorithm
Java Program to Implement Sieve Of Atkin
Hướng dẫn sử dụng Java String, StringBuffer và StringBuilder
Adding a Newline Character to a String in Java
Java Program to Create a Random Linear Extension for a DAG
Java Program to Implement Fibonacci Heap
Hướng dẫn Java Design Pattern – Builder
Working with Tree Model Nodes in Jackson
Java Program to Implement Tarjan Algorithm
Sorting Query Results with Spring Data
List Interface trong Java