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 Check if any Graph is Possible to be Constructed for a Given Degree Sequence
Guide to the ConcurrentSkipListMap
Java Program to Compute Determinant of a Matrix
Java Program to Implement HashMap API
Read an Outlook MSG file
Java Program to Search for an Element in a Binary Search Tree
Lớp Collectors trong Java 8
The Modulo Operator in Java
Dockerizing a Spring Boot Application
Java Program to Implement Binary Search Tree
Testing an OAuth Secured API with Spring MVC
Java Program to Check Cycle in a Graph using Topological Sort
Java Program to Find Median of Elements where Elements are Stored in 2 Different Arrays
Adding a Newline Character to a String in Java
Spring Boot - Building RESTful Web Services
Spring Cloud – Tracing Services with Zipkin
Java 14 Record Keyword
Kiểu dữ liệu Ngày Giờ (Date Time) trong java
Converting a Stack Trace to a String in Java
Apache Commons Collections SetUtils
Spring REST API + OAuth2 + Angular
Use Liquibase to Safely Evolve Your Database Schema
Rest Web service: Filter và Interceptor với Jersey 2.x (P1)
Java Program to Implement Levenshtein Distance Computing Algorithm
Constructor Dependency Injection in Spring
Spring Boot - Enabling Swagger2
Java Program to Describe the Representation of Graph using Adjacency Matrix
Changing Annotation Parameters At Runtime
How to Read a File in Java
How to use the Spring FactoryBean?
Java 8 Streams peek() API
Java Stream Filter with Lambda Expression