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 implement Sparse Vector
Spring REST API + OAuth2 + Angular
Spring MVC Custom Validation
Java Program to Implement WeakHashMap API
Query Entities by Dates and Times with Spring Data JPA
HttpClient 4 – Send Custom Cookie
Java Program to Implement Sorted Circularly Singly Linked List
Java Program to Find Minimum Number of Edges to Cut to make the Graph Disconnected
Java Program to Generate a Random Subset by Coin Flipping
Java Program to Find Location of a Point Placed in Three Dimensions Using K-D Trees
The SpringJUnitConfig and SpringJUnitWebConfig Annotations in Spring 5
Introduction to Spring Method Security
Extract links from an HTML page
Spring @RequestParam Annotation
New Features in Java 10
Hướng dẫn sử dụng luồng vào ra nhị phân trong Java
Java Program to Implement Control Table
Giới thiệu HATEOAS
Hamcrest Collections Cookbook
Stack Memory and Heap Space in Java
Java Program to Implement ArrayList API
Java Program to Implement Dijkstra’s Algorithm using Set
Java Program to Check if it is a Sparse Matrix
Sao chép các phần tử của một mảng sang mảng khác như thế nào?
A Guide to HashSet in Java
Java Program to Check whether Directed Graph is Connected using BFS
Java Program to Perform the Shaker Sort
Hướng dẫn Java Design Pattern – Singleton
How to Read a File in Java
Java Program to Implement Miller Rabin Primality Test Algorithm
Custom Thread Pools In Java 8 Parallel Streams
Java Program to Remove the Edges in a Given Cyclic Graph such that its Linear Extension can be Found