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:
Spring MVC and the @ModelAttribute Annotation
Hướng dẫn Java Design Pattern – Chain of Responsibility
Java Program to Implement an Algorithm to Find the Global min Cut in a Graph
Java Program to Represent Graph Using Adjacency List
A Guide to Concurrent Queues in Java
Removing all Nulls from a List in Java
Spring Cloud Bus
Spring 5 WebClient
Array to String Conversions
Recommended Package Structure of a Spring Boot Project
Retrieve User Information in Spring Security
String Operations with Java Streams
Mix plain text and HTML content in a mail
Spring 5 Functional Bean Registration
Java Timer
How to Get the Last Element of a Stream in Java?
Java Program to Find Nearest Neighbor for Dynamic Data Set
Java Program to Implement Stack using Linked List
Java Program to Check whether Undirected Graph is Connected using DFS
OAuth2.0 and Dynamic Client Registration
Multi Dimensional ArrayList in Java
Request Method Not Supported (405) in Spring
How to Store Duplicate Keys in a Map in Java?
JUnit5 @RunWith
Java Program to Implement the Edmond’s Algorithm for Maximum Cardinality Matching
Java Program to Implement Solovay Strassen Primality Test Algorithm
4 tính chất của lập trình hướng đối tượng trong Java
Java Program to Perform Searching Using Self-Organizing Lists
Java Program to Implement Jarvis Algorithm
Sử dụng CyclicBarrier trong Java
What is Thread-Safety and How to Achieve it?
Java Program to Implement Euclid GCD Algorithm