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 8 Streams peek() API
Comparing Strings in Java
Java Program to Check for balanced parenthesis by using Stacks
Spring Boot Security Auto-Configuration
Read an Outlook MSG file
Sao chép các phần tử của một mảng sang mảng khác như thế nào?
Converting String to Stream of chars
Một số từ khóa trong Java
Java Program to Implement Binary Tree
Using Spring @ResponseStatus to Set HTTP Status Code
StringBuilder vs StringBuffer in Java
Finding Max/Min of a List or Collection
Quick Guide to java.lang.System
Spring Boot - Google Cloud Platform
Reading an HTTP Response Body as a String in Java
Circular Dependencies in Spring
Create a Custom Exception in Java
How to Round a Number to N Decimal Places in Java
Quick Guide on Loading Initial Data with Spring Boot
New Features in Java 9
Spring Data MongoDB Transactions
Spring MVC Content Negotiation
How to Add a Single Element to a Stream
Custom HTTP Header with the HttpClient
Java Program to Find Nearest Neighbor for Dynamic Data Set
Working with Tree Model Nodes in Jackson
Phân biệt JVM, JRE, JDK
Creating a Custom Starter with Spring Boot
So sánh Array và ArrayList trong Java
Java Program to Check Whether a Given Point is in a Given Polygon
A Guide to Java HashMap
Java Program to Implement the Binary Counting Method to Generate Subsets of a Set