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:
Wrapper Classes in Java
Quick Guide to Spring MVC with Velocity
Java Program to Solve Travelling Salesman Problem for Unweighted Graph
Spring Boot - Enabling Swagger2
Toán tử instanceof trong java
How to Add a Single Element to a Stream
Tính trừu tượng (Abstraction) trong Java
An Example of Load Balancing with Zuul and Eureka
Java Program to Implement Regular Falsi Algorithm
Java Program to Implement Fisher-Yates Algorithm for Array Shuffling
Java Program to Implement First Fit Decreasing for 1-D Objects and M Bins
Java Program to Implement the Binary Counting Method to Generate Subsets of a Set
A Guide to JUnit 5 Extensions
How to use the Spring FactoryBean?
Intro to Spring Boot Starters
Guide to java.util.concurrent.Locks
Java Program to Implement Quick Hull Algorithm to Find Convex Hull
Converting String to Stream of chars
Java Program to Implement the Bin Packing Algorithm
Tính kế thừa (Inheritance) trong java
Hướng dẫn Java Design Pattern – Interpreter
Java Program to Implement Nth Root Algorithm
File Upload with Spring MVC
Java Program to Implement Find all Back Edges in a Graph
Default Password Encoder in Spring Security 5
Java Program to Compare Binary and Sequential Search
Exploring the Spring 5 WebFlux URL Matching
Spring RestTemplate Error Handling
The Guide to RestTemplate
Spring Cloud Bus
Immutable Objects in Java
Java Program to Represent Graph Using Adjacency Matrix