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:
New Features in Java 15
Converting a Stack Trace to a String in Java
Java Program to Perform the Unique Factorization of a Given Number
Java Program to do a Breadth First Search/Traversal on a graph non-recursively
Java Program to Implement Stack
RestTemplate Post Request with JSON
Java Program to Use Dynamic Programming to Solve Approximate String Matching
Spring AMQP in Reactive Applications
Spring Boot - Web Socket
Giới thiệu JDBC Connection Pool
Java Program to Implement SynchronosQueue API
Create a Custom Auto-Configuration with Spring Boot
The Spring @Controller and @RestController Annotations
Java Program to implement Dynamic Array
Class Loaders in Java
HttpClient 4 Cookbook
Java Program to Implement WeakHashMap API
Optional trong Java 8
Collect a Java Stream to an Immutable Collection
Jackson Ignore Properties on Marshalling
Java Program to Implement Multi-Threaded Version of Binary Search Tree
How to Iterate Over a Stream With Indices
Java Program to Find the Minimum value of Binary Search Tree
Chương trình Java đầu tiên
Hướng dẫn Java Design Pattern – DAO
Java – Get Random Item/Element From a List
Guide to CountDownLatch in Java
Practical Java Examples of the Big O Notation
CharSequence vs. String in Java
Intro to Inversion of Control and Dependency Injection with Spring
Creating Docker Images with Spring Boot
Custom HTTP Header with the HttpClient