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 Create a Random Linear Extension for a DAG
Java Program to Find SSSP (Single Source Shortest Path) in DAG (Directed Acyclic Graphs)
Properties with Spring and Spring Boot
Kiểu dữ liệu Ngày Giờ (Date Time) trong java
Java Program to Implement Attribute API
So sánh HashSet, LinkedHashSet và TreeSet trong Java
Hướng dẫn Java Design Pattern – Observer
The Order of Tests in JUnit
Map Serialization and Deserialization with Jackson
Java Program to Implement Direct Addressing Tables
How to Round a Number to N Decimal Places in Java
Query Entities by Dates and Times with Spring Data JPA
Redirect to Different Pages after Login with Spring Security
Java Program to Find the Connected Components of an UnDirected Graph
Java Program to Implement wheel Sieve to Generate Prime Numbers Between Given Range
Creating a Generic Array in Java
Câu lệnh điều khiển vòng lặp trong Java (break, continue)
Lớp Collections trong Java (Collections Utility Class)
Java – Convert File to InputStream
Check if there is mail waiting
Java Program to Implement the RSA Algorithm
Java Program to Implement Network Flow Problem
Java Program to Represent Graph Using 2D Arrays
Spring Security 5 – OAuth2 Login
Java Program to Implement Fenwick Tree
Java Program to Implement Knight’s Tour Problem
Java Program to Perform Partition of an Integer in All Possible Ways
Java Program to Implement Aho-Corasick Algorithm for String Matching
Java Program to Check Whether Graph is DAG
Using Java Assertions
Collect a Java Stream to an Immutable Collection
Java – Reader to String