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:
HTTP Authentification and CGI/Servlet
Guide to PriorityBlockingQueue in Java
A Guide to the finalize Method in Java
Convert a Map to an Array, List or Set in Java
Java Program to Implement Ternary Heap
Default Password Encoder in Spring Security 5
ExecutorService – Waiting for Threads to Finish
Creating Docker Images with Spring Boot
Java Program to Evaluate an Expression using Stacks
Spring’s RequestBody and ResponseBody Annotations
Hướng dẫn sử dụng luồng vào ra nhị phân trong Java
Java – Rename or Move a File
Từ khóa throw và throws trong Java
Java Program to Implement Hash Tables Chaining with Binary Trees
Biến trong java
Java Program to Implement Heap
Autoboxing và Unboxing trong Java
Java Program to Implement Pollard Rho Algorithm
Spring Data MongoDB Transactions
Spring Data JPA Delete and Relationships
Spring Boot - Rest Template
Removing all duplicates from a List in Java
Java Program to Implement Shell Sort
Concatenating Strings In Java
Spring Boot Gradle Plugin
Lập trình mạng với java
Feign – Tạo ứng dụng Java RESTful Client
A Comparison Between Spring and Spring Boot
Derived Query Methods in Spring Data JPA Repositories
Overview of Spring Boot Dev Tools
Java Program to Implement a Binary Search Algorithm for a Specific Search Sequence
OAuth2 for a Spring REST API – Handle the Refresh Token in Angular