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:
Guide to Guava Multimap
Immutable ArrayList in Java
Binary Numbers in Java
Java Program to Give an Implementation of the Traditional Chinese Postman Problem
Java Program to Implement Weight Balanced Tree
Versioning a REST API
Spring Boot - Batch Service
Java Program to Compute DFT Coefficients Directly
Java Program to Check if a Matrix is Invertible
Java Program to Represent Graph Using Incidence List
Java Program to Find Transitive Closure of a Graph
The Spring @Controller and @RestController Annotations
Spring Boot - Code Structure
Java Program to Create the Prufer Code for a Tree
Practical Java Examples of the Big O Notation
Primitive Type Streams in Java 8
Weak References in Java
Java Program to Implement Selection Sort
Deploy a Spring Boot WAR into a Tomcat Server
Functional Interfaces in Java 8
Java Program to Construct an Expression Tree for an Infix Expression
A Quick JUnit vs TestNG Comparison
Introduction to Using Thymeleaf in Spring
Spring Boot - Unit Test Cases
Spring RestTemplate Error Handling
Flattening Nested Collections in Java
Java Program to Implement RenderingHints API
Java String to InputStream
Java Program to Implement Expression Tree
Java Program to Implement Jarvis Algorithm
Service Registration with Eureka
RegEx for matching Date Pattern in Java