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 Stack
Encode a String to UTF-8 in Java
Java Program to Check Whether a Given Point is in a Given Polygon
Allow user:password in URL
Tránh lỗi NullPointerException trong Java như thế nào?
Converting a Stack Trace to a String in Java
How to Get All Spring-Managed Beans?
Java Program to Implement a Binary Search Algorithm for a Specific Search Sequence
Java 8 StringJoiner
Java Program to Implement LinkedHashMap API
An Intro to Spring Cloud Security
Spring 5 Testing with @EnabledIf Annotation
Java List UnsupportedOperationException
Java Program to Implement Ford–Fulkerson Algorithm
Java Program to Check if a Given Graph Contain Hamiltonian Cycle or Not
Java Web Services – JAX-WS – SOAP
Multipart Upload with HttpClient 4
Functional Interfaces in Java 8
Introduction to Spring Data REST
Extra Login Fields with Spring Security
Guide to the Java ArrayList
Removing all duplicates from a List in Java
Hashing a Password in Java
Receive email using POP3
Hướng dẫn Java Design Pattern – Transfer Object
Java Copy Constructor
Java Program to Find Number of Spanning Trees in a Complete Bipartite Graph
Hướng dẫn sử dụng luồng vào ra ký tự trong Java
Reactive WebSockets with Spring 5
Java Program to Implement TreeSet API
Spring Boot - Internationalization
Java Convenience Factory Methods for Collections