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 Generate a Graph for a Given Fixed Degree Sequence
Java – Delete a File
Guide to Apache Commons CircularFifoQueue
4 tính chất của lập trình hướng đối tượng trong Java
Java Program to Create a Random Graph Using Random Edge Generation
Java Program to Implement Attribute API
Java Program to Implement Direct Addressing Tables
Giới thiệu Google Guice – Injection, Scope
Cơ chế Upcasting và Downcasting trong java
Tạo số và chuỗi ngẫu nhiên trong Java
Using a Spring Cloud App Starter
MyBatis with Spring
Guide to the Java ArrayList
Debugging Reactive Streams in Java
Java Program to Implement Horner Algorithm
Java Program to Optimize Wire Length in Electrical Circuit
A Guide to the finalize Method in Java
JUnit5 @RunWith
Hướng dẫn Java Design Pattern – Composite
Why String is Immutable in Java?
Java Program to Describe the Representation of Graph using Adjacency Matrix
Map Serialization and Deserialization with Jackson
Compact Strings in Java 9
Convert Hex to ASCII in Java
Convert String to Byte Array and Reverse in Java
Java Program to Use rand and srand Functions
Guide to Spring 5 WebFlux
The Registration Process With Spring Security
Java Program to Implement LinkedHashSet API
Creating a Generic Array in Java
Spring Boot - Cloud Configuration Client
LinkedHashSet trong java