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:
Introduction to the Java NIO2 File API
Java Program to Perform Quick Sort on Large Number of Elements
Java Program to Implement PrinterStateReasons API
Hashing a Password in Java
Spring Security OAuth2 – Simple Token Revocation
Redirect to Different Pages after Login with Spring Security
Apache Tiles Integration with Spring MVC
Spring Boot - Exception Handling
Java – Reader to Byte Array
Java Program to Implement Euler Circuit Problem
So sánh HashMap và Hashtable trong Java
How to Iterate Over a Stream With Indices
Giới thiệu về Stream API trong Java 8
Getting a File’s Mime Type in Java
Exploring the Spring 5 WebFlux URL Matching
How to use the Spring FactoryBean?
Upload and Display Excel Files with Spring MVC
Java Program to Implement Binomial Heap
Inheritance with Jackson
Java Program to Solve Tower of Hanoi Problem using Stacks
Lớp Collectors trong Java 8
Spring Data JPA @Query
Assert an Exception is Thrown in JUnit 4 and 5
Easy Ways to Write a Java InputStream to an OutputStream
A Guide to the ResourceBundle
Java Program to Implement Selection Sort
Spring Boot - Bootstrapping
@Lookup Annotation in Spring
Java Program to Implement Quick sort
Guide to the Synchronized Keyword in Java
Java Program to Implement Gale Shapley Algorithm
Life Cycle of a Thread in Java